Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a LinkedHashSet to an EnumSet in Java?

I am trying to make a bean for converting LinkedHashSet into an EnumSet. This is required because Neo4j needs a conversion class for this situation. I have implemented the class so far as:

public class LinkedHashSetToEnumSet implements Converter<LinkedHashSet<Access>, EnumSet<Access>> {

    @Override
    public EnumSet<Access> convert(LinkedHashSet<Access> h) {
        EnumSet<Access> e = new EnumSet<Access>(); // error here
        // Somehow do a for loop to add all of e to h?
        return e;
    }

} 

I get an error where I have the commented line // error here where the error is:

Cannot instantiate the type EnumSet<Resource.Access>

Is there some simple thing that I am missing here for creating an EnumSet?

EDIT:

Is it possible to convert a HashSet into an EnumSet?

like image 326
Stephen D Avatar asked Dec 15 '22 06:12

Stephen D


1 Answers

The error is clear: EnumSet doesn't have constructors, the only way to create one is using the static methods in the class, that receive actual enum values. If you need to create an EnumSet with all of the elements in a LinkedHashSet, try this:

public EnumSet<Access> convert(LinkedHashSet<Access> h) {
    return EnumSet.copyOf(h)
}

I don't think it's necessary to have a class and a method for this, simply call copyOf() whenever necessary and pass as a parameter any Collection of enum values.

like image 69
Óscar López Avatar answered Jan 06 '23 02:01

Óscar López