拆箱装箱
装箱:基本类型 ——> 包装类型
拆箱:包装类型 ——> 基本类型
jdk 5之前需要手动拆箱装箱
int a = 100;
Integer i1 = new Integer(a); //装箱
Integer i2 = new Integer("123")
int a2 = i1.intValue(); //拆箱 注意 intValue这个int其他包装类要改
jdk9 之后 Integer(int value) 和 Integer(String s) 构造方法已经过时了,不建议使用
jdk 5(包括5)之后自动拆箱装箱
int n2 = 100;;
Integer i1 = n2; //自动装箱 底层:Integer.valueOf(n2)
int n3 = i1; //自动拆箱 底层:i1.intValue()
要点
三元运算符
Object obj1 = true ? new Interger(1) : new Double(2.0);
这里直接 true 执行 new Integer(1) ,但是三元运算符是一个整体,后面又Double 要类型提升,所以 obj1 = 1.0;
比较问题
- 注意堆区
Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.println(i == j);
可以看到这里有 new i 和 j 指向两个不同的堆空间,==对于引用类型要比较的是地址,所以输出 false
- 注意底层
Integer i = 1;
Integer j = 1;
System.out.println(i == j);
前面说过 这种自动装箱底层是 Integer.valueOf(1);所以比较的时候我们要追一下源码分析一波,可以发现源码意思是:如果是 -128 ~ 127 会被缓存,在这个范围内,指向的都是内存中相同的实例。没在这个范围就直接创建对象返回,这里两个哦都是 1 直指向相同实例, 所以这里是 true,
- 有基本数据类型
Integer i = 200;
int j = 200;
System.out.println(i == j);
如果是有基本数据类型直接比较值是否相等
String - 包装类 - 基本数据类型互转
public class Main {
public static void main(String[] args) {
//String ---> int
String s1 = "123";
int i1 = Integer.parseInt(s1);
System.out.println(i1);
//int ---> String
int i2 = 123;
//第一种
String s2 = i2 + "";
System.out.println(s2);
//第二种
String s3 = Integer.toString(i2);
System.out.println(s3);
//String --> Integer
String s4 = "123";
Integer i3 = Integer.valueOf(s4);
//Integer --> String
String s5 = String.valueOf(i3);
//int --> Integer
int i4 = 100;
Integer i5 = Integer.valueOf(i4);
//Integer --> int
int i6 = i5.intValue();
}
}