Reputation: 1949
I have a large enum declared in my class
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
}
since only one instance of each CarMaker is needed, is it a bad practice if I want to use this enum as a storage (like an array but instead access each element using indices, I could use more intuitive names. Also I can have custom functions for each element)
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
Right now A and B seem to create their own instance of "Honda", but I want them to be shared. Is it possible?
Upvotes: 1
Views: 165
Reputation: 285403
Use your enum but via composition: Create an enum of brand names, but then build your objects that need a name to hold a field of the enum.
Example
public enum CarMaker {
Honda,
Toyota,
Sony,
Olympus,
Facebook,
Google,
...
}
public class Car {
CarMaker carMaker;
//... etc....
Car(CarMaker carMaker) {
this.carMaker = carMaker;
// ... more code
}
//....
Upvotes: 2
Reputation: 44808
enum
s are supposed to be immutable constants. Giving them a public, modifiable field is a horrible idea.
Upvotes: 5