一、封装类
当我们需要对基础数据类型进行对象的操作时,就要用到封装类。即对基础数据类型进行封装,并用它生成对象。
八种数据类型所对应的封装类如下:
byte——Byte
short——Short
int——Integer
long——Long
float——Float
double——Double
boolen——Boolen
char——Character
示例:
Integer x = new Integer("19");
二、自动装箱与自动拆箱
自动装箱:
将基本数据类型自动转换为对应的包装类型。
示例代码:(将int类型的变量x自动装箱为Integer类型的对象y)
public class ex1
{
public static void main(String[] args)
{
int x = 19;
Integer y = x;//Integer y = new Integer("19"); y=x;
System.out.println(x==y);
}
}
Integer在装箱过程中调动了Integer中的valueOf()方法 。
自动拆箱:
将包装类型自动转换为对应的基本数据类型。
示例代码:(将Integer类型的对象自动拆箱为int类型的变量)
public class ex1
{
public static void main(String[] args)
{
Integer x = 19;//Integer x = new Integer("19");
int y = x;
System.out.println(x==y);
}
}
Integer在拆箱过程中调用了Integer中的intValue()方法。
三、常见问题
- 示例代码:
public class ex1
{
public static void main(String[] args)
{
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a==b);
System.out.println(c==d);
}
}
分析:在装箱过程中,调用了valueOf()方法,即128超过了-128到127的这个范围,给c和d赋值时,直接返回new Integer(),属于两个不同的对象,结果为false;而127在范围内,给a和b赋值时,直接返回cache[ ]数组中的对象,属于同一个对象,结果为true。
- 示例代码:
public class ex1
{
public static void main(String[] args)
{
Double a = 127.0;
Double b = 127.0;
Double c = 128.0;
Double d = 128.0;
System.out.println(a==b);
System.out.println(c==d);
}
}
分析:Double封装类的valueOf是返回一个新的封装类对象,因此都为false。
-
总结:
Double派别:即Double、Float的valueOf()方法的实现是类似的,每次都返回不同的对象。
Integer派别:Integer、Short、Byte、Character、Long的valueOf()方法的实现是类似的,每次根据数据大小返回对象,有可能两次返回同一个对象,也可能是不同对象。