EnumSet.copyOf empty collection throws IllegalArgumentException

user11412208 :

I have below code which fails with IllegalArgumentException

public EnumSet<test> getData(){  // Line 1
   return EnumSet.copyOf(get(test))) // Line 2
}



private Collection<Test> get(Test[] test){  //Line 1
 test= test==null ? new Test[0] : test;     // line 2
 return Array.asList(test) //Line 3
}

if test is null , then line 2 of get function creates empty array of Test and EnumSet.copyOf(get(test)) throws IllegalArgumentException

I dont understand why this exception is thrown ?

erickson :

An EnumSet uses some reflection to identify the type of its elements. (The set uses the "ordinal" of the enum values to track whether each element is included or not.)

When you create an EnumSet with copyOf(Collection), it checks to see if the collection is an EnumSet. If it is, it uses the same type as the source set. Otherwise, it attempts to call getClass() on the first element in the source collection. If the collection is empty, there is no first element, and nothing to query for its class. So it fails in that case ("throws IllegalArgumentException if c is not an EnumSet instance and contains no elements").

To create an empty EnumSet, you need to determine the class yourself, and use noneOf().

Collection<Test> tests = get(test);
return tests.isEmpty() ? EnumSet.noneOf(Test.class) : EnumSet.copyOf(tests);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77044&siteId=1