Using static factory methods is preferred over using constructors, especially when using simple types. The virtual machine can cache such calls, or the method can return a reference to an already defined (immutable) Object instead of creating a new Object for every invocation.
Another advantage, though debatable, is the usage of ==
for factory-created types:
(new Boolean(true) == new Boolean(true))
will return false, but
(Boolean.valueOf(true) == Boolean.valueOf(true))
will return true.
Since 0.6
Bad code: |
Good code: |
|
Integer i = new Integer("5"); |
Integer i = Integer.valueOf("5"); |
|
This code check requires Eclipse to resolve bindings. Enabling this code check increases build time.
The quick fixes for this code check replaces the new operator with a static method invocation.