4

I've created an enum in Java with each element of the enum referencing another enum. I've also implemeneted a getter which would return the referenced instance. Nothing weird or wrong, I'd say. The only difference from the usual enum implementation is the use of another enum as the backing value. I don't use int or any other primitive type.

Then I tried to implement the other enum in the same way and use the first enum as the backing value for its elements. The code compiles fine and nothing appears to be wrong until I called the getter a few times.

See for yourself in the below JUnit test. The assertion fails on the last line.

Why does it fail?

import static org.junit.Assert.assertNotNull;
import org.junit.Test;

enum EN {
    DOG(CS.PES),
    CAT(CS.KOCKA);

    CS v;

    EN(CS v) {
        this.v = v;
    }

    public CS getCS() {
        return this.v;
    }
}

enum CS {
    PES(EN.DOG),
    KOCKA(EN.CAT);

    EN v;

    CS(EN v) {
        this.v = v;
    }

    public EN getEN() {
        return this.v;
    }
}

public class EnumTest {

    @Test
    public void testValueOfEnum() {
        String zvire = "PES";
        CS pes = CS.valueOf(zvire);
        assertNotNull(pes);
        assertNotNull(pes.getEN()); // OK
        assertNotNull(pes.getEN().getCS()); // FAIL -- getCS() is null
    }
}
  • As a side comment, an enum is not the best way to create a dictionary - but maybe that was just an example. – assylias Jul 18 '16 at 11:11
  • No proof here but since I believe an enum is basicly a class with static instance (or simply constante), one is always create before the other, so the enum instance may not be instranciated yet. Just an idea ;) – AxelH Jul 18 '16 at 11:12
  • 3
    That's because you have a circular reference (A refers to B and B refers to A), which causes a problem with the initialization - to initialize A, first B must be initialized and vice versa. – Jesper Jul 18 '16 at 11:12

0 Answers0