package Equals; public class IntegerEquals { public static void main(String[] args) { printLine(128); Integer a=128; Integer b=128; System.out.println(a==b); System.out.println(a.equals(b)); printLine(127); a=127; b=127; System.out.println(a==b); System.out.println(a.equals(b)); printLine(-128); a=-128; b=-128; System.out.println(a==b); System.out.println(a.equals(b)); printLine(-129); a=-129; b=-129; System.out.println(a==b); System.out.println(a.equals(b)); } private static void printLine(int flag) { System.out.println("========"+flag+"========"); } }
Output:
========128======== false true ========127======== true true ========-128======== true true ========-129======== false true
原因:
基于减少对象创建次数和节省内存的考虑,[-128,127]之间的数字会被缓存。
[-128,127]这个范围取决于java.lang.Integer.IntegerCache.high参数的设置。
private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
时间: 2024-10-22 04:52:49