I\'ve recently discovered an interesting way to create a new instance of an object in Google Guava and Project Lombok: Hide a constructor behind a static creator method. Thi
There are a number of reasons why you might prefer a static factory method instead of a public constructor. You can read Item 1 in Effective Java, Second Edition for a longer discussion.
EnumSet.of(E)
will return a different type if the emum type has very few elements vs if the enum type has many elements (Edit: in this particular case, improving performance for the common case where the enum doesn't have many elements)Integer.valueOf(x)
will, by default, return the same object instance if called multiple times with the same value x
, if x
is between -128 and 127.java.util.concurrent.Executors
.Collections
hides many types. Instead of having a Collections
class with many static methods, they could have created many public classes, but that would have been harder for someone new to the language to understand or remember. List strings = new ArrayList()
in Guava you can do List strings = Lists.newArrayList()
(the newArrayList
method is a generic method, and the type of the generic type is inferred).For HashBiMap
, the last reason is the most likely.