Why do Guava classes provide so many factory methods instead of just one that takes varargs? [duplicate]

天涯浪子 提交于 2019-11-29 13:18:44

The comment in the source says:

// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(

So, this was done because varargs methods produce a warning with generic arguments.

I think it's to avoid unchecked generic array creation warning when E is a generic type.

It's to avoid the overhead of creating a varargs array for the most common use cases. This is modeled after the way EnumSet.of(..) was designed.

Actaully the compiler is really dumb, the JVM has most of the smarts, but its still not smart enough to eliminate the need to create an array for a vararg.

Whether saving the array is really worth it, is perhaps something the author didn't want users to worry about. i.e. he might know it doesn't make much difference, but not all users might realise its not worth worrying about it 99% of the time.

When it was google-collections this was part of the description "High-performance immutable implementations of the standard collection types, for example ImmutableSet"

What I can think of is to avoid confusion by the compiler.

If we had only,

public static ImmutableList<E> of(E element); //Option 1

and

public static ImmutableList<E> of(E... elements);  //Option 2

and in your code we had

ImmutableList<String> list = ImmutableList.of("Value");

The compiler wouldn't know whether to call option 1 or option 2.

There must be a valid reason why Josh Bloch, Kevin Bourrillion and his team thought of having "ridiculous" of(...) method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!