Can Java enum class set default value

Mycode is

public enum PartsOfSpeech2 { n("noun"), wp("标点"), a("adjective"), d("conjunction"), ...;

which I want

public enum PartsOfSpeech2 { n("noun"), wp("标点"), a("adjective"), d("conjunction"), %("noun");

can I hava a default value which is not in it, can it be set as a default value? because I have a type is "%", but enum is not support %, so I want a default value to solve it

1

3 Answers

The default for one who holds a reference to an enum without setting a value would be null (either automatically in case of a class field, or set by the user explicitly).

Unfortunately you cannot override the method valueOf for your own enum, as it is static.

But you can still create your methods:

public enum PartsOfSpeech2 { n("noun"), wp("标点"), a("adjective"), d("conjunction"); private String value; PartsOfSpeech2(String value) { this.value = value; } // declare your defaults with constant values private final static PartsOfSpeech2 defaultValue = n; private final static String defaultString = "%"; // `of` as a substitute for `valueOf` handling the default value public static PartsOfSpeech2 of(String value) { if(value.equals(defaultString)) return defaultValue; return PartsOfSpeech2.valueOf(value); } // `defaultOr` for handling default value for null public static PartsOfSpeech2 defaultOr(PartsOfSpeech2 value) { return value != null ? value : defaultValue; } @Override public String toString() { return value; }
}

From JLS 8.9. Enums

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1).

So you can't have any instance which is take default value.

You can create default constant and use that using some condition.

public enum PartsOfSpeech2 { .... DEFAULT("DEFAULT");
}

And use condition to check if your string have constant, Ex "%" have enum or not. if not use default value:

PartsOfSpeech2 result = PartsOfSpeech2.valueOf("%"); //Your String EX: %
PartsOfSpeech2 resultNew = result==null?PartsOfSpeech2.DEFAULT: result;
0

The way I solved it was the following

public enum YourEnum{
ENUM1("stringToMatchWith"),
ENUM2("stringToMatchWith2"),
DEFAULTENUM("Default");
public final String label;
YourEnum(String label) { this.label = label;
}
public static YourEnum resolveYourEnum(String stringToMatch) { return Arrays.stream(YourEnum.values()).filter(aEnum -> aEnum.label.equals(stringToMatch)).findFirst().orElse(YourEnum.DEFAULTENUM);
}

That way you can do YourEnum.resolveYourEnum("aString") and return the specified enum or the default we set

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like