Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error in enum with static initializer

Tags:

java

enums

I'm currently working on a project (database implementation) involving an enum class called ElementType with a inner enum called TypeType. Inside ElementType there is a HashMap<TypeType, ArrayList<ElementType>> mapping all the ElementType's to their corresponding TypeType values.

The values of TypeType are

[TEXT, NUMERIC_EXACT, NUMERIC_APPROX, OTHER]

The values of ElementType (and their corresponding TypeType) are

[CHARACTER(TEXT), CHAR(TEXT), DECIMAL(NUMBER_EXACT), DEC(NUMBER_EXACT), NUMERIC(NUMERIC_EXACT), INTEGER(NUMERIC_EXACT), INT(NUMERIC_EXACT), SMALLINT(NUMERIC_EXACT), FLAT(NUMERIC_APPROX), REAL(NUMERIC_EXACT), DOUBLE_PRECISION(NUMERIC_APPROX), DOUBLE(NUMERIC_APPROX), DATE(OTHER), TIME(OTHER), VARCHAR(OTHER), LONG_VARCHAR(OTHER)]

And in a static {} area, I have this code:

for(ElementType eType : values()) {
    TypeType t = eType.getTYPE();
    if(typeMapping.get(t) != null)
        typeMapping.get(t).add(eType);
    else
        typeMapping.put(t, new ArrayList<ElementType>() {add(eType);});
}

All of the eType mentions within the for loop are underlined red within Eclipse.

The first one gives the error eType cannot be resolved.

The second one gives eType cannot be resolved to a variable.

And the third one (inside the ArrayList) gives Syntax error on token "eType", VariableDeclaratorId expected after this token.

The getTYPE() method is private and returns the TypeType for each ElementType. The typeMapping is the HashMap mentioned above.

I don't know what is causing this or how to fix it, does anyone know how to fix this, or what I can do?

like image 600
Robert Allen Avatar asked Mar 27 '26 15:03

Robert Allen


1 Answers

The problem is here:

typeMapping.put(t, new ArrayList<ElementType>() {add(eType);});
                                                ^^^^^^^^^^^^^  

You try to create an inner, non-static class derived from ArrayList inside a static initializer block. If you replace that with a plain new ArrayList plus alist.add(eType) it will work.

OR you can use:

typeMapping.put(t, new ArrayList<ElementType>() {{add(eType);}});

Note 1: There must be two opening and closing braces. Hence the terminus "double brace initialization".

Note 2: For DBI you must make eType final in the loop.

Although I have to admit, that the error messages are ahem somewhat unclear.

like image 161
A.H. Avatar answered Mar 29 '26 05:03

A.H.