前言: 我们知道java有八大基本数据类型,如何将八大基本数据类型变为引用类型(对象),用到了java中的包装类。 在基本数据类型和包装类之间的转换,就有了自动装箱(Auto Boxing)和自动拆箱(Auto Unboxing)。
Integer n = 100; // 编译器自动使用Integer.valueOf(int) int x = n; // 编译器自动使用Integer.intValue()注意:自动拆装箱时null是引用类型才具有的,因此将其赋予基本数据类型会出现错误。
所有的包装类型都是final类型的,都是不可变。 因为所有的包装类是引用类型,所以在比较时不能用’==’,要用’equals()’。
创建Integer的方法有两种:
方法1:Integer n = new Integer(100);//总是创建实例对象 方法2:Integer n = Integer.valueOf(100);//静态工厂方法,节省内存方法二更好。
注:所有的浮点型和整型的包装类型都继承自Number
// 向上转型为Number: Number num = new Integer(999); // 获取byte, int, long, float, double: byte b = num.byteValue(); int n = num.intValue(); long ln = num.longValue(); float f = num.floatValue(); double d = num.doubleValue();