EnumSet does not consider my enumeration to be an enumeration

Inside my production code, I create an EnumSet inside an enumeration constructor, but it cannot detect that my class is an actual enumeration. This error destroys my real production code.

I used the following class for testing, but even in this small example, it could not recognize the enumeration. How can I mark my class as an enumeration in the way that EnumSet knows this enumeration?

Simple source code:

package test; import java.util.*; // Set, EnumSet, Arrays public enum Alphabet { A, B(A), C(A, B), D(A, B, C), // You get the point ; Set<Alphabet> prevLetters; Alphabet() { prevLetters = EnumSet.noneOf(Alphabet.class); // <- EnumSet here } Alphabet(Alphabet... prev) { this(); prevLetters.addAll(Arrays.asList(prev)); } public static void main(String[] args) { System.out.println(Arrays.toString(Alphabet.values())); } } 

An exception:

 Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.ClassCastException: class test.Alphabet not an enum at java.util.EnumSet.noneOf(EnumSet.java:112) at test.Alphabet.<init>(Test.java:13) at test.Alphabet.<clinit>(Test.java:4) 
+5
source share

Source: https://habr.com/ru/post/1236223/


All Articles