基本数据类型包装类
- 包装类?
java 给每种基本数据类型提供了包装类,用类来封装基本数据类型,并提供了一些便捷的方法供我们使用
-
八大数据类型的包装类
基本数据类型 包装类 byte Byte short Short int Integer long Long float Float double Double boolean Boolean char Character int的包装类的写法为Integer、char的包装类的写法是:Character
其余基本数据类型的包装类均是基本类型的首字母大写。
-
装箱 : 把基本数据类型包装为对应的包装类对象
-
// int ==》 Integer Integer i1 = new Integer(1); Integer i4 = new Integer(1); Integer i2 = Integer.valueOf(1); Integer i5 = Integer.valueOf(1); Integer i3 =1; System.out.println(i2==i5); //true System.out.println(i1==i4); //false System.out.println(i1==i2); //false System.out.println(i1==i3); //false System.out.println(i2==i3); //true
i2 ==i3 说明,自动装箱,底层调用的是 valueOf()方法;
valueOf()源码
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
IntegerCache 在这个数组里面存有值为-128到127的Integer类的实例,如果调用valueOf方法时,所取的值在这个范围里面,那么就可以直接从cache里面拿取相应的类,而不用新new一个,从而减小开销; cache数组范围可以在启动时调节jvm参数设置;
若超出范围,就重新new 一个新对象 ,也就说跟直接使用构造函数效果类似;
普通构造源码:
public Integer(int value) { this.value = value; }
这也就解释了为啥 上面i1 != i4了, 构造了两个对象,而非拿IntegerCache数组里的值;
-
-
拆箱 :把包装类对象转换为对应的基本数据类型。
-
int a = i1.intValue(); int a = i1; //自动拆箱
-
jdk1.5开始 ,提供了自动装箱,拆箱的语法糖 ,即 将基本数据类型和包装类型直接用等号连接 ;
-
与字符串的相互转换
-
//String ==> int String str = "12"; int i = Integer.parseInt(str); int j =new Integer(str); //本质上也是在构造函数里调用parseInt()方法 System.out.println(i); System.out.println(j); //int ==>String String s = Integer.toString(i); System.out.println(s); String s1 = String.valueOf(i); System.out.println(s1);
-