简体   繁体   中英

Java enum elements with spaces?

Im working on java, I have created an enum as follows:

public enum myEnum
{
    india,
    russian,
    england,
    north America
}

Above example gives errors while using space in the name of element (ie north America). Any suggestions how to resolve above issue?

You can't put a space in the middle of an identifier.

Doing so ends that identifier and the parser assumes whatever comes next is a valid token in that statement's context. There are few (if any) places that would be legal.

Conventional Java value names would be:

INDIA,         // Or  India,
RUSSIA,        //     Russia,
NORTH_AMERICA; //     NorthAmerica;

An enum can have associated properties, like human-readable names, eg,

public enum CountryAndOneContinent {

    INDIA("India"),
    RUSSIA("Russia"),
    NORTH_AMERICA("North America");

    private String displayName;

    CountryAndOneContinent(String displayName) {
        this.displayName = displayName;
    }

    public String displayName() { return displayName; }

    // Optionally and/or additionally, toString.
    @Override public String toString() { return displayName; }
}

I'm ambivalent about using toString to provide presentation-layer representations.

I prefer methods communicate their purpose explicitly–it's more expressive and obvious.

toString is pretty generic, and allows only a single representation. Multiple output formats may be required depending on context, parameters, etc. which toString doesn't allow.

Advantages of toString include using default string operations on the object, and in this case, using valueOf to directly translate from the human-readable version to the enum value.

I'm gong to go ahead and guess why you want a space in the name; because you want to reference it as a string.

So do this:

public enum MyEnum {
    INDIA("India"),
    RUSSIAN("Russian"),
    ENGLAND("England"),
    NORTH_AMERICA("North America");    

    private String name;

    MyEnum(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }    
}

You can consider overriding string.

public toString() {
    return name;
}

An advantage of overriding toString() is that this string can also be used in MyEnum .valueOf(myString). So overriding toString basically creates a HashMap of the enum values.

The problem has nothing (specifically) to do with enums: in Java, names can't have spaces. Try eliminating the space (using capitalization to tell the bits apart) or use underscores instead.

将它们像northAmerica一样写在一起或使用下划线north_America

The Java naming rule does not allow white spaces as possible characters in a name of variables, classes, enums and enum members (and every other identifier). Therefore this "problem" cannot be resolved. Just use `north_america' as member name!

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.

The Java letters include uppercase and lowercase ASCII Latin letters AZ (\A-\Z), and az (\a-\z), and, for historical reasons, the ASCII underscore (_, or \_) and dollar sign ($, or \$). The $ character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.

The "Java digits" include the ASCII digits 0-9 (\0-\9).

just make your own valueOf like function in your enum class. Replace spaces with underscores. name your enum constants like this "north_america("North America")". If the method fails to find your enum it just returns the parameter.

public  static String valueOfOrDefault(String myValue) {
//replace space with underscore so it matches enum name
        String value=myValue.toUpperCase().replaceAll("\\s", "_");
        for(myEnum type : myEnum.class.getEnumConstants()) {
          if(type.name().equalsIgnoreCase(value)) {
            return type.toString();
          }
        }
        return myValue;
      }

I also introduced an own valueOf method. But I return with the Enum Type and I do not have to convert the "checkString"

checkString is "Petty Cash" for example.

JournalType journalType = JournalType.valueOfOrDefault(checkString);

With the following enum:

public enum JournalType {

MISC_BILLING("Misc Billing"),
MISC_BILLING_AUTONUM("Misc Billing AutoNum"),
PRETTY_CASH("Petty Cash"),
RECURRING_AP("Recurring AP"),
GL_JOURNAL("GL Journal"),
GDS_NDS("GDS/NDS");

private final String journalType;

JournalType(String journalType) {
    this.journalType = journalType;
}

@Override
public String toString() {
    return journalType;
}

public static JournalType valueOfOrDefault(String myValue) {
    for(JournalType type : JournalType.class.getEnumConstants()) {
        if(type.toString().equals(myValue)) {
            return type;
        }
    }
   throw new IllegalArgumentException("JournalType not found");
}

}
public enum myEnum
{
    india,
    russian,
    england,
    north_america
}

To access values

myEnum.values()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM