包装类
1.位置:位于Java的lang包下,所以可以直接使用。
2.理解:八种数据类型的都有对应的包装类。在实际应用中经常需要将基本数据类型转化为对象来使用。提供包装类给便于操作。
3.作用:
(1)某些方法的参数必须是一个类,为了更加方便的使用基本数据类型的数据,所以要提供包装类。
List list=new ArrayList();
list.add(new Integer(20));
list.add(new Integer(30));
System.out.println(list);
(2)包装类还提供了更多的功能。包装类提供类很多的方法,可以实现不同的功能。并且很多方法是static方法,可以直接使用类名来调用。
System.out.println(Integer.toBinaryString(66));
System.out.println(Integer.toHexString(66));
System.out.println(Integer.SIZE);
System.out.println(Integer.MAX_VALUE);
(3)可以实现字符串和数值的转换
System.out.println(Integer.parseInt("99")-Integer.parseInt("88"));
4.注意:
(1).包装类既既占用栈内存,也占用堆内存。而基本数据类型只占用堆内存。
(2).包装类的引用变量初始值为null,而基本数据类型的的初始值为0.
(3)。除了Boolean类型和Character类型外,其他的6个包装类的父类都是Number类。
5.自动装箱和自动拆箱
Integer in1=20;//自动装箱
int b=in1;//自动拆箱
(2)在包装类的源码中,有一个静态的数组static final Integer cache[];
这样就是说,只要你调用了Integer类就会在元空间内创建一个数组,默认的长度是256cache = new Integer[(high - low) + 1];
通过下面的代码就实现了数组的赋值(-128—127)
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
当你使用调用Integer类时,如果输入的数字是在(-128—127)范围之内,那么引用变量会指向之前已经创建好数组中数的地址,所以如果你输入的数字相等的,那么两个变量就指向了同一个地址,使用==时,会发现是true。但如果不在(-128—127)的范围内,就会创建新的Integer的对象。
演示如下:
Integer in2=1234;
Integer in3=1234;
System.out.println(in2==in3);
System.out.println(in2.equals(in3));
Integer in4=123;
Integer in5=123;
System.out.println(in4==in5);
System.out.println(in4.equals(in5));