If you are asking whether you can create an enum
where the constants have spaces, then the answer is 'no'.
Enum constants are normal Java identifiers, like class or variable names so they can not have spaces or special characters in them.
However is it impossible to link an enum with a String? No.
If for some reason you want your switch case to use an enum
for readability/brevity, but your inputs are Strings
that can have spaces, dots, special characters..., then there is a way.
You need to extend your enum
to have an extra field (let's call it label) to hold this String
.
In your method with the switch case that uses the enum
, you can call a findByLabel
method
that returns the enum
that corresponds to the provided String
.
Here is a little example class that uses your enum
values NORTH, EAST, SOUTH, WEST,
linked to Strings
of different (invalid enum naming) structures.
public class EnumExample {
enum SwitchEnum {
NORTH ("North star"),
EAST ("Eastpack rulez!"),
SOUTH ("https://www.southafrica.net/"),
WEST ("java.awt.BorderLayout.WEST");
private final String label;
SwitchEnum(final String label) {
this.label = label;
}
@Override
public String toString() {
return this.label;
}
private static final Map<String,SwitchEnum> map;
static {
map = new HashMap<String,SwitchEnum>();
for (SwitchEnum v : SwitchEnum.values()) {
map.put(v.label, v);
}
}
public static SwitchEnum findByLabel(String label) {
return map.get(label);
}
}
public static String doEnumSwitch(String enumString) {
SwitchEnum enm = SwitchEnum.findByLabel(enumString);
if (enm != null) {
String enumReturn = enm.name() +" : "+ enm;
switch (enm) {
case NORTH:
return enumReturn +" - Up there.";
case EAST:
return enumReturn +" - Now for sale.";
case SOUTH:
return enumReturn +" - Now with 50% more elephants.";
default:
return "UNHANDLED ENUM : "+ enm.name() +" - "+ enm;
}
} else {
return "UNKNOWN ENUM : "+ enumString;
}
}
public static void main(String[] args) {
System.out.println(doEnumSwitch("North star"));
System.out.println(doEnumSwitch("Eastpack rulez!"));
System.out.println(doEnumSwitch("https://www.southafrica.net/"));
System.out.println(doEnumSwitch("java.awt.BorderLayout.WEST"));
System.out.println(doEnumSwitch("I only want to get out of here."));
}
}
This outputs the following
NORTH : North star - Up there.
EAST : Eastpack rulez! - Now for sale.
SOUTH : https://www.southafrica.net/ - Now with 50% more elephants.
UNHANDLED ENUM : WEST - java.awt.BorderLayout.WEST
UNKNOWN ENUM : I only want to get out of here.