我在课堂上声明了一个大型枚举
public enum CarMaker{
Honda,
Toyota,
Sony,
...;
public CarMaker at(int index){ //a method to retrieve enum by index
CarMaker[] retval = this.values();
return retval[index];
}
public final SomeObj val; //a value associated with each enum
//.. more custom functions if needed
}
由于只需要每个 CarMaker 的一个实例,如果我想将此枚举用作存储(如数组但使用索引访问每个元素,我可以使用更直观的名称,我可以使用自定义函数),这是一种不好的做法对于每个元素)
CarMaker A = CarMaker.Honda;
CarMaker B = CarMaker.at(1);
//Error above b/c 'at' is not a static member, can I make at a static member?
A.val = 5;
B.val = 6;
//Here I want A to be share data with B since both are "Honda"
//but it doesn't seem to do that yet
System.out.println(A)
System.out.println(B)
//Expected output:
//A: 6
//B: 6
现在 A 和 B 似乎创建了他们自己的“Honda”实例,但我希望它们被共享。可能吗?