8中基本的包装类型
在java中基本数据类型是不面向对象的,而有很多时候要用到对象,所以对于基本数据类型来说,就会不适用,因此在java中引入了8中包装类
基本数据类型变量中存储的就是原始值,
包装类型属于引用数据类型,变量中存储的是存储原始值地址的引用。
Integer类型与int类型之间的区别与转化
public class WrappedTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//将基本数据类型转换为包装类型
Integer a=new Integer(3);
Integer b=Integer.valueOf(3);
//将包装类型转换成基本数据类型
int c=b.intValue();
double d=b.doubleValue();
//将字符串转换成包装类型
Integer e=new Integer("999");
Integer f=Integer.parseInt("1234");
//将包装类型转换为字符串类型
String s=f.toString();
String s1=""+f;
}
}
自动装箱和拆箱
这个过程是编译器自动完成的。
自动装箱:
基本类型的数据处于需要对象的环境中时,会自动转换为“对象”(包装类)。
自动拆箱:
每当需要一个值时,对象会自动转换成基本数据类型,没有必要再去显式的调用intValue()等转型方法。
public class WrappedTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//自动装箱
Integer a=234;//编译器会将其转化为Integer a=Integer.valueOf(234);
//自动拆箱
int b=a;//编译器会自动转化为int b=a.intValue();
Integer c=null;
//int d=c;//java.lang.NullPointerException
//因为会自动拆箱,会自动调用c.intVaule()的方法。所以会报空指针异常的错误。
if(c!=null) {
int d=c;
}
}
}
关于缓存[-128,127]范围之间的数字问题
Integer a=-128;
Integer n1=1234;
在java中对于在【-128,127】之间的数与其他范围之间的数在定义时有些不同,java将在[-128,127]之间的数放在了一个数组中,所以每当定义一个该范围的数时,就会找到该数组中的对应位置,所以在定义了两个值相同的不同变量是,两个变量指向的都是在数组中的同一个位置。
如果不在该范围之内的话,没定义一个变量,就会通过new创建一个新的对象,所以即使是值相同的两个变量,其也是属于不同的对象。
以下是对于该内容的详细测试
public class WrappedTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer n1=1234;
Integer n2=1234;
System.out.println(n1==n2);//false
System.out.println(n1.equals(n2));//true
System.out.println("___________________________");
Integer a=-128;
Integer b=-128;
System.out.println(a==b);//true
System.out.println(a.equals(b));//true
/*在java的源码中,Integer.valueOf()会先判断该数值是否存放在low=-128,high=127
* 之间,如果在这个范围之间,则该函数返回的就是一个cache数组中的值,
* 如果数值超过了这个范围,就会重新new一个对象
*
* public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
*/
/*
* cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
*/
}
}