是否可以/可能修改枚举声明中的实例变量?
或者,重新表述一下:枚举类型可以是“可变的”吗?
public enum Foo {
ONE,TWO;
private String bar;
Foo() { this.bar = ""; }
String bar() { return bar; }
// legal?
void bar(String bar) { this.bar = bar; }
}
我想如果我想修改它,它就不再是枚举类型了。
想法?
Or, to re-phrase it: can enum types be "mutable"?
public enum Foo {
ONE,TWO;
private String bar;
Foo() { this.bar = ""; }
String bar() { return bar; }
// legal?
void bar(String bar) { this.bar = bar; }
}
I guess if I want to modify it, it's no longer an enum type.
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是绝对有效的。这真是个坏主意。调用者可能期望枚举是完全不可变的。在某些情况下,您可能希望使其“看起来”是不可变的,例如通过缓存,同时仍然改变内部变量......但这很大程度上是一种边缘情况。
至于为什么 Java 允许你这样做......即使它强制所有成员变量都是最终的,这也不会让枚举值真正不可变......例如,你可以有一个
List
每次调用特定方法时都会对其进行修改...从根本上讲,Java 不太擅长强制执行不变性。
It's absolutely valid. It's just a really bad idea. Callers are likely to expect the enum to be properly immutable. In some cases you might want to make it "appear" to be immutable, e.g. with caching, while still mutating the internal variables... but that's very much an edge case.
As to why Java lets you do this... even if it forced all member variables to be final, that wouldn't make enum values truly immutable... for example, you could have a
List<String>
which was modified each time you called a particular method...Fundamentally, Java's not very good at enforcing immutability.