mercredi 1 mars 2017

If condition is true even then else is executing

I have an enum defined as below, which contains a static function fromString(String s) which is like valueOf(String s) but case insensitive.

enum Letter {
    A, B, C, UNKNOWN;

    private static final Map<String, Letter> stringToEnumMap = new HashMap<>();

    static {
        for (Letter letter : values()) {
            stringToEnumMap.put(letter.toString().toLowerCase(), letter);
        }
    }

    public static Letter fromString(String symbol) {
        Letter letter = stringToEnumMap.get(symbol.toLowerCase());
        if (letter != null) {
            return letter;
        } else {
            return UNKNOWN;
        }
    }
}

but when I execute the following code

Letter letter = Letter.fromString("a");

I get Letter.UNKNOWN returned. I tried debugging but that is where it got even more freaky. Debugger says letter != null is true because letter equals Letter.A. After that the code moves to else statement and UNKNOWN is return.

Any Idea?

Aucun commentaire:

Enregistrer un commentaire