I was using Sonar to make my code cleaner, and it pointed out that I'm using new Integer(1)
instead of Integer.valueOf(1)
. Because it seems that valueOf
does not instantiate a new object so is more memory-friendly. How can valueOf
not instantiate a new object? How does it work? Is this true for all integers?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
From the JavaDoc:
ValueOf
is generaly used for autoboxing and therefore (when used for autoboxing) caches at least values from -128 to 127 to follow the autoboxing specification.Here is the
valueOf
implementation for Sun JVM 1.5.? Have a look at the whole class to see how the cache is initialized.From the java.lang.Integer Source Code. Integer cache is configurable. To configure the Integer cache size other than Sun we need to use the System property
java.lang.Integer.IntegerCache.high
as per the source code.From java.lang.Short,java.lang.Byte and java.lang.Long creates a cache of 127 to -128
Integer.valueOf implements a cache for the values -128 to +127. See the last paragraph of the Java Language Specification, section 5.1.7, which explains the requirements for boxing (usually implemented in terms of the .valueOf methods).
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7
they are pushing you to use
valueOf()
instead ofnew Integer()
so the methodvalueOf()
does it for you, and caches the value in case you want to get the same number again in future. In that case, method won't instatiate new Integer, but will give you the cached one, what will make 'creation' of new Integer a lot quicker and memory friendly process..This way you may cause yourself alot of problems if you are unexperienced java programmer since you will conclude that
Integer.valueOf(342)==Integer.valueOf(342)
, because you may (or may not) have the same pointer for two Integers, and probably you will practise it in a way, let's say, you learned in C#, so that will show you bugs from time to time, and you won't know how & where those came from...