先说说int 与 Integer的区别:
Integer是int的包装类,其对象存储在堆中,对象引用在栈中,int为基本数据类型,存储在栈中
int的初值为0,Integer的初值为null
接下来你会发现一些奇怪的地方,这是我不经意的时候发现的奥秘
int i1=3;
int i2=3;
System.out.println(i1 == i2);//true,毋庸置疑,对于基本类型,比较的是值,自然是true
Integer i3=3;
Integer ii3=new Integer(3);
System.out.println(i1 == i3);//true
System.out.println(i1 == ii3);//true,一个基本类型与引用类型比较,比较的也是值
System.out.println(i3 == ii3);//false,两个引用类型比较,比较的是引用
神奇之处来了~~~~
Integer i4=127;
Integer i5=127;
System.out.println(i4 == i5);//true,对于Integer i4=127,Java在编译的时候,
被翻译为Integer i4=Integer.valueOf(127),对于valueOf方法,Integer里弄了一个缓存,对于在-128~127以内的值,会直接使用该缓存里面的对象,所以i4、i5引用相同,为true,若改为128,由于超出缓存范围,则为false,不信自己可以试试
总结一句:多么富有人性化的设计。。。。知道我们平常小整形数用的多,专门整了一下缓存。