/**
* 从java内存出发解释下面3个问题
* @author sen
*
*/
public class Test { public static void main(String[] args) {
Integer a = 128;
Integer b = 128;
System.out.println(a==b);//1.为什么是false?
int c = 128;
int d = 128;
System.out.println(c==d);//2.为什么是true?
Integer e = 128;
int f = 128;
System.out.println(e==f);//3.为什么是true?
}
}
* 从java内存出发解释下面3个问题
* @author sen
*
*/
public class Test { public static void main(String[] args) {
Integer a = 128;
Integer b = 128;
System.out.println(a==b);//1.为什么是false?
int c = 128;
int d = 128;
System.out.println(c==d);//2.为什么是true?
Integer e = 128;
int f = 128;
System.out.println(e==f);//3.为什么是true?
}
}
结果明明就是true
Integer a = 127;
Integer b = 127;
System.out.println(a==b);//结果为true,这要作何解释呢?
会调用 Integer.valueOf方法,即相当于
Integer a = Integer.valueOf(xxx)public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i); //当大于128时,返回new对象
}
public static void main(String[] args) {
Integer a = 128;
Integer b = 128;
System.out.println(a==b);//1.为什么是false? 从源码可知,大于128得到两个不同的Integer对象,==是比较两个对象本身的内存信息,它们分别保存不同Integer对象的地址,所以不同,结果为false
int c = 128;
int d = 128;
System.out.println(c==d);//2.为什么是true? 基本类型,内存信息的比较,内存都是128数值
Integer e = 128;
int f = 128;
System.out.println(e==f);//3.为什么是true?//自动拆箱机制,都转成int来比较
}
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
Integer a = 128;
Integer b = 128;debug的时候a,b的id是不一样的,所以a对象的引用和b对象的引用不同,比较引用当然不一样。另外补充一些:
基本类型(primitive types), 共有8种,即int, short, long, byte, float, double, boolean, char(注意,并没有string的基本类型)。这种类型的定义是通过诸如int a = 3; long b = 255L;的形式来定义的,称为自动变量。值得注意的是,自动变量存的是字面值,不是类的实例,即不是类的引用,这里并没有类的存在。如int a = 3; 这里的a是一个指向int类型的引用,指向3这个字面值。这些字面值的数据,由于大小可知,生存期可知(这些字面值固定定义在某个程序块里面,程序块退出后,字段值就消失了),出于追求速度的原因,就存在于栈中。
------------------------------------------------------------------
我之前说关于常量池,是在网上看了下面这段话的,那现在知道下面的这说法是不正确的啦,谢谢啊:
整型在常量池里只能表示-128到127.超过这个范围的就不归常量池管了
例如
Integer a = 128;
Integer b = 128;
a==b 返回的是false.
Integer a = 128;
性质就是
Integer a = Integer.valueOf(128);