Integer.valueOf(int i)源码中 assert
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
assert的作用是计算表达式expression,
jdk1.7中存在,1.8中源码中已删除该代码。(频繁的调用会极大的影响程序的性能,增加额外的开销)
注意:有些地方,assert不能代替过滤条件
Other:
Integer.valueOf(int i)的范围
public static void main(String[] args) { Integer a = 1; Integer b = 1; Integer c = 128; Integer d = 128; System.out.println(a==b); System.out.println(c==d);}
代码执行结果:
truefalse