Java——包装类

目录

[3.5 包装类](#3.5 包装类)


3.5 包装类

有时需要把基本类型转换为对象。所有基本类型都有一个与之对应的类。这些类称为包装器/类。这些类是不可变类,即一旦构造了包装器/类,就不允许改变包装在其中的值。其次包装类还是final,不用可以被继承。
为什么要有包装类:类当中可以定义方法,用于操作数据。基本数据类型没有操作数据的能力。所以这时候需要包装类。包装类是对基本数据类型的一个补充。
1、基本数据类型和包装类的对应关系:

2、int Integer String 之间的装换

  • int -> Integer:new Integer(int value) ; Integer.valueOf(int i)返回一个Integer型的对象。
  • Integer -> int:intValue() 返回 Integer 对象所包装的 int 值。
  • Integer ->String:toString() 返回表示该 Integer 对象数值的字符串。
  • String -> Integer:new Integer(String s)返回一个 Integer 对象,此对象包装了由字符串解析得到的 int 值。
  • int -> String:String.valueOf(int i) 返回表示该 int 值的字符串。
  • String -> int:Integer.parseInt(String s)返回表示该 int 值的字符串。
java 复制代码
public class ConversionExample {
    public static void main(String[] args) {
        // int -> Integer
        int num = 10;
        Integer integerObj1 = new Integer(num);
        Integer integerObj2 = Integer.valueOf(num);

        // Integer -> int
        int numFromInteger = integerObj1.intValue();

        // Integer -> String
        String strFromInteger = integerObj1.toString();

        // String -> Integer
        String str = "20";
        Integer integerObj3 = new Integer(str);

        // int -> String
        String strFromInt = String.valueOf(num);

        // String -> int
        int numFromString = Integer.parseInt(str);
    }
}

3、装箱:基本类型 -> 包装

java 复制代码
int a = 10;
Integer i = Integer.valueOf(a);
Integer j = new Integer(a);

4、拆箱:包装类 -> 基本类型

java 复制代码
Integer k = new Integer(10);
int b = k.intValue();

5、自动装箱:

java 复制代码
int c = 20;
Integer p_auto = c;
Integer m = 100;

6、自动拆箱:

java 复制代码
Integer l = new Integer(10);
int d_auto = l;
  1. 7、128陷阱

  2. 例子:

    num1取值在 [-128 , 127] 是true,否则false。因为Integer设置了缓存数组(缓存 [-128 , 127] 之间的所有整数,Integer型的数组)。如果自动装箱的数在 [-128 , 127] 之间,就直接返回缓存中的对象。否则,就会new一个对象。

java 复制代码
Integer num1 = 120;
Integer num2 = 120;
System.out.println(num1==num2);//true,指向同一个内存空间
Integer num3 = new Integer(100);
Integer num4 = new Integer(100);
System.out.println(num3==num4);//false
java 复制代码
Integer num1 = 150;
Integer num2 = 150;
System.out.println(num1==num2);//flase
Integer num3 = new Integer(100);
Integer num4 = new Integer(100);
System.out.println(num3==num4);//false

8.使用==判断包转类和基本数据类型是否相等时,包装类会自动拆箱,变成基本数据类型。此时,比较值是否相等。

9.包装类的 equals() 方法会比较对象的实际值(通过显式方法调用),而非引用。

例子:

相关推荐
炸膛坦客29 分钟前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
兑生1 小时前
【灵神题单·贪心】1481. 不同整数的最少数目 | 频率排序贪心 | Java
java·开发语言
daidaidaiyu1 小时前
一文学习 Spring 声明式事务源码全流程总结
java·spring
炸膛坦客2 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
零雲2 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
Jay_Franklin2 小时前
Quarto与Python集成使用
开发语言·python·markdown
2401_831824963 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~3 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you4 小时前
C++中的职责链模式实战
开发语言·c++·算法
@我漫长的孤独流浪4 小时前
Python编程核心知识点速览
开发语言·数据库·python