目录
1.1 Integer.valueOf()-->装箱(int-->Integer)
1.2 Integer.intValue()-->拆箱 (Integer-->int)
1.int和Integer的拆装箱
准备:新建文本文档,写完程序后,修改后缀名为.java(在path栏输入cmd进行测试)
注意:类名与文件名一致
javac 类名.java--> 编译
javap -c 类名 -->反编译
1.1 Integer.valueOf()-->装箱(int-->Integer)
public class Test{
public static void main(String[] args){
int a = 3;
//自动拆箱: 将对象类型转化成基本数据类型。
Integer b = a;
}
}
1.2 Integer.intValue()-->拆箱 (Integer-->int)
public class Test1{
public static void main(String[] args){
//自动装箱:自动装箱简单来说就是将数据类型封装成对象类型。
Integer a = 3;
int b = a;
}
}
2.基本数据类型和包装类的区别
基本数据类型 | 包装类型 |
不是对象 | 对象,有方法和字段,调用时通过引用对象的地址 |
值的传递 | 引用地址的传递 |
不需要new | 需要new在堆空间进行内存空间的分配 |
保存于栈中 | 保存于堆中 |
例:int初始值为0,boolean初始值为false | 初始值为null |
赋值使用 |
byte | char | short | int | long | float | double | boolean |
Byte | Character | Short | Integer | Long | Float | Double | Boolean |
3.常量池
java基本类型的包装类(Byte,Short,Integer,Long,Character)实现常量池,Integer、Long实现常量池默认创建数值[-128,127]的响应的缓存数据,超出此范围仍然会创建新的对象(即new)。而包装类Boolean,Float,Double没有实现常量池。
常量池中[-128,127]会被不断重用,都指向为同一对象,因此==时也是比较两者的引用,所以都为true,而产生常量池,是这些数字被重用次数高,存放在常量池,减少多次创建对象。
通过代码可修改(sts中)
1.Integer ctrl+鼠标左键进入源代码-->Ctrl+f 搜cache-->复制-XX:AutoBoxCacheMax=<size>
2.[sts-->Run-->Run Configurations-->java project-->页面右边的Arguments-->VM arguments -XX:AutoBoxCacheMax=<size>]
把<size>改成数字-->apply-->run
举例:Integer的常量池
public class TestDemo02 {
public static void main(String[] args) {
//Integer的常量池 -128~127 源码:range [-128, 127] must be interned
//源码:private static class IntegerCache
Integer x = 129;
Integer y = 129;
System.out.println(x==y);
Integer a = -128;
Integer b = -128;
System.out.println(a==b);
}
}
4.Integer的最值 (LeetCode中常用)
Integer.MAX_VALUE :int的最大值 (2147483647 即2^31-1)
Integer.MIN_VALUE :int的最小值(-2147483648 即-2^31)
注意:Integer.MAX_VALUE+1=Integer.MIN_VALUE
Integer.SIZE:int的二进制位数 (32位)
public class TestDemo01 {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
//基本类型int 的二进制数 Integer.SIZE
System.out.println(Integer.SIZE);
}
}