Java包装类VS基本数据类型

包装类

针对八种基本数据类型定义相应的引用类型—包装类(封装类)
有了类的特点,就可以调用类中的方法, Java才是真正的面向对象

为什么使用包装类?

基本数据类型无法通过向上转型获取到Object提供的方法,而像String却可以,只因为String是一个对象而不是一个类型。基本数据类型由于这样的特性,导致无法参与转型,泛型,反射等过程。为了弥补这个缺陷,java提供了包装类。

包装类与基本数据类型对照表

在这里插入图片描述

基本数据类型与包装类的相互转换

基本数据类型包装成包装类的实例(装箱)

  1. 通过包装类的构造器实现:

    int i = 500;
    Integer t = new Integer(i);
    
  2. 通过字符串参数构造包装类对象:

    Float f = new Float(4.56);
    
获得包装类对象中包装的基本类型变量 —拆箱

调用包装类的.xxxValue()方法:

boolean b = bObj.booleanValue();

JDK1.5之后,支持自动装箱,自动拆箱。但类型必须匹配。

自动装箱与拆箱

装箱

装箱:包装类使得一个基本数据类型的数据变成了类。有了类的特点,可以调用类中的方法。

装箱原理(调用包装类的构造器)
int i = 500;
Integer t = new Integer(i);
拆箱

拆箱:将包装类中内容变为基本数据类型

拆箱原理(调用包装类Xxx的xxxValue())
Integer t = new Integer(500);
int j = t.intValue(); // j = 500, intValue取出包装类中的数据
自动装箱与拆箱

JDK1.5之后,支持自动装箱,自动拆箱。但类型必须匹配。即包装类与基本数据类型可以直接赋值,不必再调用构造器或者xxxValue()。

示例
//自动装箱:基本数据类型 --->包装类
		int num2 = 10;
		Integer in1 = num2;//自动装箱
		
		boolean b1 = true;
		Boolean b2 = b1;//自动装箱
		
		//自动拆箱:包装类--->基本数据类型
		System.out.println(in1.toString());
		
		int num3 = in1;//自动拆箱

基本数据类型、包装类、String三者之间的相互转换

基本数据类型与包装类互相转换上文相当于上文的装箱和拆箱的原理,不在阐述。

扫描二维码关注公众号,回复: 11504418 查看本文章

包装类在实际开发中用的最多的在于字符串变为基本数据类型。

String类型 —>基本数据类型、包装类:调用包装类的parseXxx(String s)
String str1 = "123";
int num2 = Integer.parseInt(str1);
System.out.println(num2 + 1);
		
String str2 = "true1";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
基本数据类型、包装类—>String类型:调用String重载的valueOf(Xxx xxx)或者做连接运算
  1. 连接运算

    int num1 = 10;
    String str1 = num1 + "";
    
  2. 调用String重载的valueOf(Xxx xxx)

    float f1 = 12.3f;
    String str2 = String.valueOf(f1);//"12.3"
    
    Double d1 = new Double(12.4);
    String str3 = String.valueOf(d1);
    System.out.println(str2);
    System.out.println(str3);//"12.4"
    
图解基本数据类型、包装类、String三者之间的相互转换

在这里插入图片描述

思考题

1.思考下面两种方式输出的值为什么不同?

o1输出为1.0

Object o1 = true ? new Integer(1) : new Double(2.0);
System.out.println(o1);//1.0

o1输出为1

Object o2;
if (true)
o2 = new Integer(1);
else
o2 = new Double(2.0);
System.out.println(o2);//1
思考

因为三元运算操作需要保证?后的两个表达式的数据类型相同,int需要向上转型为double

2.比较下列的值是否相同
Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.println(i == j);//false

//Integer内部定义了IntegerCache结构,IntegerCache中定义了Integer[],
//保存了从-128~127范围的整数。如果我们使用自动装箱的方式,给Integer赋值的范围在
//-128~127范围内时,可以直接使用数组中的元素,不用再去new了。目的:提高效率

Integer m = 1;
Integer n = 1;
System.out.println(m == n);//true

Integer x = 128;//相当于new了一个Integer对象
Integer y = 128;//相当于new了一个Integer对象
System.out.println(x == y);//false

猜你喜欢

转载自blog.csdn.net/qq_42937522/article/details/106559655