【Java源码】Integer类

Java中Integer为32位,所以它的最大值最小值又如下:

/**
     * A constant holding the minimum value an <code>int</code> can
     * have, -2<sup>31</sup>.
     */
    public static final int   MIN_VALUE = 0x80000000;

    /**
     * A constant holding the maximum value an <code>int</code> can
     * have, 2<sup>31</sup>-1.
     */
    public static final int   MAX_VALUE = 0x7fffffff;

Integer中使用final value保存整数值,所以与String一样Integer的内容也是不可变的

/**
     * The value of the <code>Integer</code>.
     *
     * @serial
     */
    private final int value;

一、源码方法
1、Integer.valueof(444);源码中使用内部类IntegerCache缓存了-128到127的数字,所以多次valueOf(3)会得到同一个对象,而多次valueOf(333)则是不同的对象

public static Integer valueOf(int i) {
	final int offset = 128;
	if (i >= -128 && i <= 127) { // must cache 
	    return IntegerCache.cache[i + offset];
	}
        return new Integer(i);
    }
private static class IntegerCache {
	private IntegerCache(){}

	static final Integer cache[] = new Integer[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Integer(i - 128);
	}
    }
2、Integer.valueOf(String "122")与Integer.parseInt(String "111")

首先前者返回的是一个Integer对象,而后置返回一个int值,源码比较发现,他们都调用了Integer.parseInt(s, radix)方法,将数字字符串转化成radix进制数

public static int parseInt(String s) throws NumberFormatException {
	return parseInt(s,10);
    }

public static Integer valueOf(String s) throws NumberFormatException
    {
	return new Integer(parseInt(s, 10));
    }

3、hashCode(),返回对象的value

public int hashCode() {
	return value;
    }
4、intValue()返回对象的value,通常用于Integer的拆箱
public int intValue() {
	return value;
    }

二、装箱拆箱,是编译器进行的优化

1、自动装箱,.java文件中的代码如下:

Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
编译完成,class文件中的代码如下:

Integer c = Integer.valueOf(3);
Integer d = Integer.valueOf(3);
Integer e = Integer.valueOf(321);
Integer f = Integer.valueOf(321);
由valueOf(int i)这个函数的源码可知,c和d指向的是同一个对象,而e和f指向的是不同的对象
2、自动拆箱,.java文件中代码如下:

int idd = c + d;
d = c + d;
编译完成,class文件中的代码如下:
int idd = c.intValue() + d.intValue();
    d = Integer.valueOf(c.intValue() + d.intValue());






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值