一:装箱操作和拆箱操作
public class IntergerDemo {
public static void main(String[] args) {
//装箱操作:把一个基本类型的值,转换为对应包装类
//方式一:
Integer num1 = new Integer(17);
//方式二:
Integer num2 = Integer.valueOf(17);
//拆箱操作:把包装类的对象,转换为对应的基本类型变量
int num3 = num1.intValue();
int num4 = (int) num2.doubleValue();
System.out.println(num1);
System.out.println(num2);
System.out.println(num3);
System.out.println(num4);
}
}
二:自动装箱和自动拆箱
- 自动装箱:可以把基本类型变量直接赋给对应的包装类型变量
- 自动拆箱:允许把包装类对象直接赋值给对应的基本数据类型变量
Integer num5 = 12;//自动装箱
int num6 = num5;//自动拆箱
System.out.println(num5);
System.out.println(num6);
三:解释 Object obj = 17;
- Integer i = 17;//装箱操作
- Object obj = i;//自动转换类型(对象的上桩型对象)
四:常用方法,类型转换
- public abstract int intValue();返回指定数字的值为 int
- public abstract long longValue();返回指定数字的值为 long
- public abstract float floatValue();返回指定数字的值为 float
- public abstract double doubleValue();返回指定数字的值为 double
- public byte byteValue();返回指定数字的值为 byte
- public short shortValue();返回指定数字的值为 short
Float num = 123.12f;
int i = num.intValue();
short s = num.shortValue();
System.out.println(i);
System.out.println(s);
System.out.println(num);
五:String类型和包装类型之间的转换
- String类型转换成包装类,以Interger为例
//把String转换为包装类类型
String str = "1111111123";
Integer i1 = Integer.valueOf(str);
- 把包装类转换成String类型
Float f = 123.1232322f;
String str1 = f.toString();
System.out.println(str1);
- 把String转换成基本数据类型
String input = "123456";
int n = Integer.parseInt(input);
System.out.println(n);
- 把基本数据类型转成String
String str2 = 17+"";
六:包装类中的缓存设计
- Byte,Short,Integer,Long 在[-128,127]范围,就获取缓存地址;char在[0,127]]范围,就获取缓存地值
- Byte,Short,Integer,Long 不在[-128,127]范围,就开辟新的内存空间
Integer in = Integer.valueOf(45);
Integer in1 = Integer.valueOf(45);
System.out.println(in == in1);//ture
Integer in2 = Integer.valueOf(450);
Integer in3 = Integer.valueOf(450);
System.out.println(in2 == in3);//false
七:Integer和int的区别(包装类和基本数据类型的区别)
- 默认值:int为0;Integer既可以表示null,又可以表示0
- 包装类中提供了该类类型相关的很多算法
- 在集合框架中,只能存贮对象类型,不能存贮基本数据类型
- Integer和int是同一种数据类型吗?不是
- 方法中的基本数据类型变量存储到栈中,包装类型存放到堆中