Search code examples
javainitializationsetdeclaration

Creating prepopulated set in Java


In Java, how do I create a final Set that's populated at construction? I want to do something like the following:

static final Set<Integer> NECESSARY_PERMISSIONS 
    = new HashSet<Integer>([1,2,3,6]);

but I don't know the proper syntax in Java.


Solution

  • Try this idiom:

    import java.util.Arrays;
    
    new HashSet<Integer>(Arrays.asList(1, 2, 3, 6))