请教高手:Integer与int区别 ,另外发帖后该怎么怎么结贴。
public class Test2 { public static void main(String[] args) {
int a=120;
int b=120;
System.out.println(a==b);
int c=150;
int d=150;
System.out.println(c==d);
}
}
//结果 true
true public class Test2 { public static void main(String[] args) {
Integer a=120;
Integer b=120;
System.out.println(a==b);
Integer c=150;
Integer d=150;
System.out.println(c==d);
}
}
//结果 true
false
public class Test2 { public static void main(String[] args) {
Integer a=120;
Integer b=120;
System.out.println(a==b);
Integer c=150;
Integer d=c;
System.out.println(c==d);
}
}//结果 true
true
public class Test2 { public static void main(String[] args) {
int a=120;
int b=120;
System.out.println(a==b);
int c=150;
int d=150;
System.out.println(c==d);
}
}
//结果 true
true public class Test2 { public static void main(String[] args) {
Integer a=120;
Integer b=120;
System.out.println(a==b);
Integer c=150;
Integer d=150;
System.out.println(c==d);
}
}
//结果 true
false
public class Test2 { public static void main(String[] args) {
Integer a=120;
Integer b=120;
System.out.println(a==b);
Integer c=150;
Integer d=c;
System.out.println(c==d);
}
}//结果 true
true
Integer 封装类是个对象结贴就点 结贴去...
int 是变量的基本类型
Integer 是int的外覆类型
“基本类型有所谓的‘外覆类(wrapper classes)’如果你想在heap内产生用以代表该基本类型的非原始对象(nonprimitive object),那么外覆类型就可派上用场。”
引自《Thinking in Java》
Integer 是int的封装类
Integer是int的封装对象,==是比较两个引用地址是否为同一个内存地址
Integer 封装类是个对象 好像128是个自动转型的临界点,从 core java那里看来的
Integer是引用类型,==比较的是引用指向的内存地址是否相同,相同就返回true,否则返回false
Integer i = 150;
编译器调用Integer.valueOf(150)来生成Integer对象,Integer类对-128到127这些数预生成了缓存对象
在这些范围之内调用多次Integer.valueOf其实返回的是同一个内存地址的引用
而在这些范围之外则通过new Integer()的方式在堆中分配不同的内存地址
答:Integer i=120; 等价于: Integer i=Integer.valueOf(120);
而:Integer类中valueOf(int v)的实现代码是://-128 至 127 要缓存. 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 至 127 范围的数,才会每一个i都会new Integer(..)一下的.
例如:
Integer i=new Integer(0);
i++;//这是不起作用的
i=i+1;//这样才能起作用
Integer是原始数据类型的封装类..是分配在内村的堆中..也可以说一个是值传递..一个是引用传递
Integer 是个包装类
int is primitive type
Integer b=3;
等价于Integer.valueof(3)查看源文件你会发现这样做会使用该类中的静态内部类,她已经对-128到127之间的数进行缓存,调用
valueOf返回的是该静态类中的Integer而不是新创建的,所以二者比较相等。另外对整形的包装类都会对-128到127之间的数进行
缓存。
Integer 是int的封装类
基本就是这个区别
int------------------Integer
double---------------Double
float----------------Float
...........
呵,我也新手,学习中...
char Charactor
boolean Boolean
double Double
.
.
.
int变量之间用==比较时,是比较二者的数值是否相同,Integer对相之用==比较时是比较引用对相的内存地址是否相同,要比较数值就要使用equals关键字
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}看了Integer类说明····这里可以看出