Integer currentVersion = new Integer(1);
此时sonar报错,并建议使用Integer.valueOf()方法:
Constructors for String
, BigInteger
, BigDecimal
and the objects used to wrap primitives should never be used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf
for everything else.
其中Integer.valueOf的源码为:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
在-128~127的区间,Integer.valueOf并不会重新创建对象,而是使用缓存中的对象。这样可以节省内存空间。