开发者

passing ImmutableSet in place of Set?

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开发者_Python百科 I get similar error.

This works:

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

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


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. :-)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜