包装类

概述:java是面向对象语言,在实际的开发中经常需要把基本数据类型转为对象。所以包装类(Wrapper class)的作用就是把基本类型转为包装类型(对象)。

关于基本类型和包装类型请看表格:

基本类型

包装类型

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

boolean

Boolean

char

Character

除Boolean和Charcater以外,其它六个包装类都继承了Number类

让我们查看Number类的源码,在idea中按照下图操作。

查看Number类的所有方法

图中六个方法都是抽象方法,所有继承的包装类必须重写。

示例:

package com.itcode.demo4;  

/** 
 * @Auther: 成都码到功成学员 
 * @Description: 
 * 包装类测试 
 * Integer类 ,其它也差不多。 
 */  
public class TestWrapper {  

    public static void main(String[] args) {  
        // 基本类型转包装类  
        Integer aa =  new Integer(23);  
        Integer bb = Integer.valueOf(23);// 推荐  

        // 包装类转基本类型  
        int cc = bb.intValue();  
        double dd = bb.intValue();  

        // 字符串转包装类  字符串里面只能是数字,不能是字母,会报NumberFormatException  
        Integer ee = new Integer("14");  
        Integer ff = Integer.parseInt("12");  

        // 包装类转字符串  
        String gg = ff.toString();  
    }  
}

装箱拆箱

概述:JDK1.5后提供的功能。

  • 自动装箱:基本类型转包装类型。

  • 自动拆箱:包装类型转基本类型。

示例:

 Integer aa = 23 ;//自动装箱 自动调用Integer.valueOf()  
        int bb = aa;// 自动拆箱 自动调用Integer.intValue(23)  
包装类缓存问题
看代码:

```java
Integer a = 1000;  
Integer b = 1000;  
System.out.println(a == b);// false  
System.out.println(a.equals(b));// true  

Integer ab = 127;  
Integer ba = 127;  
System.out.println(ab == ba); // true  
System.out.println(ab.equals(ba));// true

==运算结果不一致是因为自动装箱的方法Integer.valueOf()。

我们去查看源码:

看到有一个IntegerCache再点进去

看到一个缓存数组,这些源码的意思是系统初始化时,会创建一个值在[-128,127]之间的数组,如果值是在这个范围内,则对象地址值一致(同一个对象)反之就是别的对象。

所以代码中a和b的对象值不一致,结果为false。

示例:

// 基本类型转包装类  
Integer aa = 23 ;//自动装箱 自动调用Integer.valueOf()  
int bb = aa;// 自动拆箱 自动调用Integer.intValue(23)  

Integer a = 1000;  
Integer b = 1000;  
System.out.println(a == b);// false  
System.out.println(a.equals(b));// true  

Integer ab = 127;  
Integer ba = 127;  
System.out.println(ab == ba); // true  
System.out.println(ab.equals(ba));// true

Last updated

Was this helpful?