Reputation: 14179
I should take from a variable enum its value and transform it to string.how can i do?
here it is the type enum:
public enum State{
b,c,p;
};
now i have to insert into an object String one value.
Upvotes: 0
Views: 197
Reputation: 21653
Method #1: Using the built-in toString()
and name()
methods
If you want to print a String
that is the same as the value of the State
, then you can use the toString()
method, or the name()
method.
System.out.println(State.b); // Prints "b"
System.out.println(State.c); // Prints "c"
System.out.println(State.p); // Prints "p"
Method #2: Using a constructor to create a custom mapping
If you want to have a custom String
associated with each of those states, you can use a constructor to associate a particular value with each enum
value:
public enum State{
b("State B"), c("State C"), p("State P");
private String longName;
private State(String longName) {
this.longName = longName;
}
@Override
public String toString() {
return this.longName;
}
};
Of course, if you don't want to break the default toString()
usage, you can create a different method called getFullName()
, for example, to return the custom value.
Upvotes: 1
Reputation: 794
I tend to do something more complicated, but I find that it's more flexible:
public enum MyEnumeration {
SOME_NAME("Some Name"),
OTHER_THING("Other Thing"),
...
MORE_VALUES("More Values"),
private final String displayName;
private MyEnumeration(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
This way, I use standard capitalization for my enums in code, but can have a more presentable name for them. This trick can also be used to replace ordinal, by initializing a number, and then you don't need to worry about rearranging your enums.
Upvotes: 1
Reputation: 5326
Usually,
State state = ...;
String string = state.toString();
should work, but it is not recommended since someone might override toString
for some other purpose.
Instead the method you are looking for is
String string = state.name();
As an aside, your enumerated stated should always be all in capitals, and they should have descriptive names. It's not a language rule, but a convention. For example enum State { ON, OFF, PAUSED; }
.
Upvotes: 2
Reputation: 21409
State.b.toString()
will return "b"
. The same goes for the other ones.
Upvotes: 2
Reputation: 72626
you can use name() or toString(), so :
State aState = State.c;
String strState = aState.name();
See here the official java reference for more information...
Upvotes: 2
Reputation: 4143
You might use enum.name
orenum.toString
to get the name of the enum constant, or enum.ordinal
to get the ordinal position.
Upvotes: 2