views:

52

answers:

2

I have a method that expects a Set parameter. I want to pass in an empty set, and I don't want any side effects on the Set.

I can do this with collections by passing in:

 Collections.unmodifiableSet(Sets.newHashSet())

But I want to pass in:

 ImmutableSet.of()

If I do the former a Set<Object> is created and I get "method not applicable for args Set' error. If I do the latter I get ImmutableSet<Object> is created and I get similar error.

This works:

 Collections.unmodifiableSet(new HashSet<String>())

... but seems ugly, and I want to find a Google Collections way.

+8  A: 

Try this:

ImmutableSet.<String>of()

This will work too:

Collections.<String>emptySet()

This syntax is useful for manually specifying type arguments any time the type inference fails. :-)

Chris Jester-Young
A: 

This will also work:

public static void main(String[] args) {
    Set<String> emptySet = ImmutableSet.of();
    doStuffWith(emptySet);
}

static void doStuffWith(Set<String> strings) {
    // ...
}

because the type inference notices that you are assigning to a Set<String> variable and knows that the type parameter must be String.

finnw