Pure Danger Tech


navigation
home

Arrays.asSet() ?

05 Apr 2007

Right now we’ve got Arrays.asList(), but not the equivalent:

public static <T> Set<T> asSet(T... values) {
        return new HashSet<T>(Arrays.asList(values));
    }

Actually, this would technically be a little different since asList() creates a List backed by the array you pass it (changes to the list write through to the array) but my asSet() will effectively copy the items in the list into the set, so the returned set is not backed by the array. But given the circumstances where asList() is normally used, I’m not sure it matters.

This can also be useful in some circumstances where you are tempted to use Collections.singleton() but you really want to return a mutable Set with a single element, not an immutable singleton set.