Suppose I have a Enum defined something like this:
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getValue()),
B(AClass.getValue()),
C(AClass.getValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
I can pull out values using Sample.A
or Sample.A.getAVal()
without issue.
Now suppose that AClass.getValue()
could take a parameter to return a possibly different particular value, eg AClass.getValue(42)
.
It is possible to pass arguments to a public Enum method and retrive the Enum values? In other words, could I have an Enum definition like
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getAValue()),
B(AClass.getBValue()),
C(AClass.getCValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public int getVal(int a){
// somehow pull out AClass.getAValue(a)
}
using Sample.A.getValue(42)
?
Of course if you could create an instance of some other base type which has a getValue(int x) method, then you could put the code into the enum class itself instead of into the nested ones.
By default enums have their own string values, we can also assign some custom values to enums.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.
Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to use the Switch case with Enum.
You can do it, but only by making an abstract method in the enum, and overriding it in each value:
public enum Sample {
A(AClass.getAValue()) {
@Override public int getVal(int x) {
return AClass.getAValue(x);
}
},
B(BClass.getAValue()) {
@Override public int getVal(int x) {
return BClass.getBValue(x);
}
},
C(CClass.getAValue()) {
@Override public int getVal(int x) {
return CClass.getCValue(x);
}
};
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public abstract int getVal(int x);
}
Of course if you could create an instance of some other base type which has a getValue(int x)
method, then you could put the code into the enum class itself instead of into the nested ones.
As stated in Java Specification
there is only one instance of each enum constant
So no, you can't have different values of a specific enum constant.
But you could put an array or a map inside your enum, so Sample.A.getValue(42)
would return Sample.A.myMap.get(42)
:
public enum Sample{
A(),
B(),
C();
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public int getVal(int i){
return myMap.get(i);
}
public int setVal(int i, int v){
return myMap.put(i, v);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With