【JDK源码】Integer

一、继承关系

在这里插入图片描述
Byte、Short、Integer、Long、Float、Double 都直接继承抽象父类 Number,该类提供了将 Number 类型的数据,转换成相对应的基本数据类型的方法。

public abstract class Number implements java.io.Serializable {
    
    public abstract int intValue();

    public abstract long longValue();

    public abstract float floatValue();

    public abstract double doubleValue();

    public byte byteValue() {
        return (byte)intValue();
    }

    public short shortValue() {
        return (short)intValue();
    }

    private static final long serialVersionUID = -8742448824652078965L;
}

二、属性 & 构造器

private final int value;

public Integer(int value) {
       this.value = value;
}

public Integer(String s) throws NumberFormatException {
	this.value = parseInt(s, 10); // 10 为 十进制的意思
}

三、缓存类

 private static class IntegerCache {
        static final int low = -128;
        static final int high; // 127
        static final Integer cache[];

四、拆箱 & 装箱

(1)装箱 valueOf:int -> Integer

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
  • 如果 i 的值在 -128 ~ 127之间,则直接返回缓存类中缓存数组cache中的值。
  • 如果 i > 128,则直接创建一个新的 Integer 返回。

(2)拆箱 intValue:Integer -> int

public int intValue() {
        return value;
}

五、创建案例

Integer i = 10; // Integer i = Integer.valueOf(10); 第一次声明,将 i 放入缓存
Integer j = 10; // 第二次直接从缓存中取
System.out.println(i == j); // true


Integer m = 128; // Integer i = Integer.valueOf(128); 超过 127,直接新建一个对象,不放入缓存
Integer n = 128; // 超过 127,直接新建一个对象,不放入缓存
System.out.println(m == n); // false


int a = 10;
System.out.println(j == a); // true,j 自动拆箱,比较的是基本数据类型

int b = 128;
System.out.println(n == b); // true,n 自动拆箱,比较的是基本数据类型

Integer x = new Integer(66); // 直接创建新对象
Integer y = new Integer(66); // 直接创建新对象
System.out.println(x == y); // false 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值