This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Problem: The best way to create string enumerations
What is the best way to represent a set of strings with an enumerated type
I try this:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")}Copy the code
How can I use them like strings?
Answer a
I don’t know what you want to do, but I can convert your sample code to:
package test;
/ * * *@author The Elite Gentleman
*
*/
public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO");private final String text;
/ * * *@param text
*/
Strings(final String text) {
this.text = text;
}
/* (non-Javadoc) * @see java.lang.Enum#toString() */
@Override
public String toString(a) {
returntext; }}Copy the code
Or, you can write a getter method to get the text
You can use strings.string_one.tostring (); the
Answer two
Produce ONE using the name() method
public class Main {
public static void main(String[] args) throws Exception { System.out.println(Strings.ONE.name()); }}enum Strings {
ONE, TWO, THREE
}
Copy the code
Answer three
You can use string enumerations like this
public enum EnumTest {
NAME_ONE("Name 1"),
NAME_TWO("Name 2");
private final String name;
/ * * *@param name
*/
private EnumTest(final String name) {
this.name = name;
}
public String getName(a) {
returnname; }}Copy the code
And it’s called inside the main function
public class Test {
public static void main (String args[]){ System.out.println(EnumTest.NAME_ONE.getName()); System.out.println(EnumTest.NAME_TWO.getName()); }}Copy the code
Answer four
You can set the enumeration name to be the same as the string you want, or, more generally, you can associate any property with your enumeration value
enum Strings {
STRING_ONE("ONE"), STRING_TWO("TWO");
private final String stringValue;
Strings(final String s) { stringValue = s; }
public String toString(a) { return stringValue; }
// further methods, attributes, etc.
}
Copy the code
It is important to place constants at the bottom and methods and properties at the bottom.
Answer five
Use default values for GET and set
public enum Status {
STATUS_A("Status A"), STATUS_B("Status B"),
private String status;
Status(String status) {
this.status = status;
}
public String getStatus(a) {
returnstatus; }}Copy the code
The article translated from Stack Overflow:stackoverflow.com/questions/3…