包装类
JAVA提供了俩种数据类型:基本数据类型和引用数据类型
引用数据类型,其实就是各种JAVA jdk提供的类
包装类只要用在泛型< E >中
很多时候,我们需要创建对象来解决问题,如ArrayList< E >,其中E必须是一个引用数据类型,如果想使用基本数据类型,就必须使用基本数据类型对应的引用数据类型,即包装类。
包装类在将基本数据类型包装为引用数据类型的同时,也定义了对基本数据类型操作的方法
@Test
public void cc(){
//包装类 Integer Float 。。。
//String -->Int
//String-->Integer
String a="88";
int i = Integer.parseInt(a);
System.out.println(i);
String b="88";
Integer j = new Integer(b);
System.out.println(j);
//int-->Integer
//int-->String
int a1=88;
Integer i1 = new Integer(a1);
System.out.println(i1);
int b1=88;
String j1 = String.valueOf(b1);
System.out.println(i1);
//Integer-->int
//Integer-->String
Integer a3=new Integer(88);//或者new Integer("88");
int i2 = a3.intValue();
System.out.println(i2);
Integer B3=new Integer(88);//或者new Integer("88");
String s = B3.toString();
System.out.println(s);
}
//3个对象直接一共有6种转换方法
// 其中 Integer 用了三种 Integer.parseInt() Integer.intvalue() Integer.toString()
//String 用了一种 String.ValueOf()
//后面会有新特性
}
1. java.lang包中的Integer类是我们比较常用的类,比如以下代码:
Integer a=new Integer(1)
Integer a=Integer.valueOf(1);
两个都是得到一个Integer对象;但是Inter.valueOf 的效率更高,Inter.valueOf 用到了缓存机制。
其中Integer.valueOf方法代码如下:
1. public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
在这个类中使用到了一个辅助类IntegerCache,IntegerCache的源码为:
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
可以看到在IntegerCache中已经初始化了cache数组。所以,要注意的是, new Integer返回的永远是不同的对象,但是当整数范围在-128<i<=127时,Integer.valueOf返回的是同一个对象。
看下面代码:Integer a=new Integer(1);
Integer b=new Integer(1);
//整数范围在-128到127之间,返回的是同一个对象
Integer c=Integer.valueOf(1);
Integer d=Integer.valueOf(1);
//返回的不是同一个对象
Integer e=Integer.valueOf(200);
Integer f=Integer.valueOf(200);
System.out.println(a==b);
System.out.println(c==d);
System.out.println(e==f);
程序运行的结果为:
false
true
false
结论:在没有对Integer创建有特殊要求时,比如纯数字计算或比较,最好用Integer.valueOf。
//3个对象直接一共有6种转换方法
// 其中 Integer 用了三种 Integer.parseInt() Integer.intvalue() Integer.toString()
//String 用了一种 String.ValueOf()
//后面会有新特性
1.为什么要有包装类(或封装类)?
为了使基本数据类型的变量具有类的特征,引入包装类。
2.基本数据类型与对应的包装类:
3.需要掌握的类型间的转换:(基本数据类型、包装类、String)
4.简易速记
基本数据类型<—>包装类:------------JDK 5.0 新特性:自动装箱 与自动拆箱
基本数据类型、包装类—>String:------调用String重载的valueOf(Xxx xxx)
String—>基本数据类型、包装类:------调用包装类的parseXxx(String s)
注意:转换时,可能会报NumberFormatException