基本类型和包装类型的区别

基本类型和包装类型的区别

简介

Java 的每个基本类型都对应了一个包装类型,比如说 int 的包装类型为 Integer,double 的包装类型为 Double。基本类型和包装类型的区别主要有以下 4 点

1.包装类型可以为 null,而基本类型不可以

它使得包装类型可以应用于 POJO 中,而基本类型则不行
POJO:简单无规则的 Java 对象,只有属性字段以及 setter 和 getter 方法,示例如下。

 1 class Writer {
 2     private Integer age;
 3     private String name;
 4 
 5     public Integer getAge() {
 6         return age;
 7     }
 8 
 9     public void setAge(Integer age) {
10         this.age = age;
11     }
12 
13     public String getName() {
14         return name;
15     }
16 
17     public void setName(String name) {
18         this.name = name;
19     }
20 }

为什么 POJO 的属性必须要用包装类型?
《阿里巴巴 Java 开发手册》上有详细的说明
数据库的查询结果可能是 null,如果使用基本类型的话,因为要自动拆箱(将包装类型转为基本类型,比如说把 Integer 对象转换成 int 值),就会抛出 NullPointerException 的异常。

2.包装类型可用于泛型,而基本类型不可以

List<int> list = new ArrayList<>();
 // 提示 Syntax error, insert "Dimensions" to complete ReferenceType
List<Integer> list = new ArrayList<>();

 

3.基本类型比包装类型更高效

基本类型在栈中直接存储的具体数值,而包装类型则存储的是堆中的引用

 
 

相比较于基本类型而言,包装类型需要占用更多的内存空间。假如没有基本类型的话,对于数值这类经常使用到的数据来说,每次都要通过 new 一个包装类型就显得非常笨重。
两个包装类型的值可以相同,但却不相等

Integer chenmo = new Integer(10);
Integer wanger = new Integer(10);

System.out.println(chenmo == wanger); // false
System.out.println(chenmo.equals(wanger )); // true

两个包装类型在使用“==”进行判断的时候,判断的是其指向的地址是否相等。将“==”操作符应用于包装类型比较的时候,其结果很可能会和预期的不符。

4.自动装箱和自动拆箱

有了基本类型和包装类型,肯定有些时候要在它们之间进行转换。
把基本类型转换成包装类型的过程叫做装箱
反之,把包装类型转换成基本类型的过程叫做拆箱
在 Java SE5 之前,开发人员要手动进行装拆箱


Integer chenmo = new Integer(10);  // 手动装箱
int wanger = chenmo.intValue();  // 手动拆箱

Java SE5 为了减少开发人员的工作,提供了自动装箱与自动拆箱的功能

Integer chenmo  = 10;  // 自动装箱
int wanger = chenmo;     // 自动拆箱

等价于
=>

Integer chenmo = Integer.valueOf(10);
int wanger = chenmo.intValue();

也就是说,自动装箱是通过Integer.valueOf()完成的;自动拆箱是通过 Integer.intValue() 完成的
特别注意:

当需要进行自动装箱时,如果数字在 -128 至 127 之间时,会直接使用缓存中的对象,而不是重新创建一个对象
// 1)基本类型和包装类型
int a = 100;
Integer b = 100;
System.out.println(a == b);//true

// 2)两个包装类型
Integer c = 100;
Integer d = 100;
System.out.println(c == d);//true

// 3)
Integer c = 200;
Integer d = 200;
System.out.println(c == d);//false

转自:https://www.jianshu.com/p/c2260088e2b8

原文地址:https://www.cnblogs.com/ScarecrowAnBird/p/13607744.html