开发者

passing ImmutableSet in place of Set?

开发者 https://www.devze.com 2022-12-18 02:21 出处:网络
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 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

精彩评论

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