Reputation: 317
I have a enum which looks like:
public enum Constants{
YES("y"), NO("N")
private String value;
Constants(String value){
this.value = value;
}
}
I have a test class which looks like
public class TestConstants{
public static void main(String[] args){
System.out.println(Constants.YES.toString())
System.out.println(Constants.NO.toString())
}
}
The output is:
YES
NO
instead of
Y
N
I am not sure what is wrong here ??
Upvotes: 29
Views: 176088
Reputation: 4415
The elegant way to get value of an Enum is by using ordinal method.
public enum Constants
{
YES("Y"), NO("N");
private String value;
public String getResponse() {
return value;
}
Constants(String value){
this.value = value;
}
public static Constants getConstants(int value){
for(Constants e : Constants.values()){
if(value == e.getResponse()) return e;
}
return null;
}
}
public class TestConstants{
public static void main(String[] args)
{
System.out.println(Constants.YES.ordinal());
System.out.println(Constants.NO.ordinal());
}
}
Upvotes: 0
Reputation: 5894
String enumValue = Constants.valueOf("YES")
Java doc ref: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)
Upvotes: 0
Reputation: 133
Create a getValue() method in your enum, and use this instead of toString().
public enum Constants{
YES("y"), NO("N")
private String value;
Constants(String value){
this.value = value;
}
}
public String getValue(){
return value;
}
And instead of:
System.out.println(Constants.YES.toString())
System.out.println(Constants.NO.toString())
(Which are also missing a semi-colon), use
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());
Hope this solved your problem. If you do not want to create a method in your enum, you can make your value field public, but this would break encapsulation.
Upvotes: 12
Reputation: 3656
You can also add a getter to the enumeration and simply call on it to access the instance variable:
public enum Constants{
YES("Y"), NO("N");
private String value;
public String getResponse() {
return value;
}
Constants(String value){
this.value = value;
}
}
public class TestConstants{
public static void main(String[] args){
System.out.println(Constants.YES.getResponse());
System.out.println(Constants.NO.getResponse());
}
}
Upvotes: 17
Reputation: 17142
You need to override the toString
method of your enum:
public enum Constants{
YES("y"), NO("N")
// No changes
@Override
public String toString() {
return value;
}
}
Upvotes: 39
Reputation: 3603
Write Getter and Setter for value
and use:
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());
Upvotes: 7