JDK源码 -- Integer

2019-08-19  本文已影响0人  TomyZhang

一、概念

类定义:

public final class Integer extends Number implements Comparable<Integer>

特点:

二、使用

//TestInteger
public class TestInteger {
    private static final String TAG = "TestInteger";
    private Integer integer = new Integer(64);

    public void testEquals() {
        Log.d(TAG, "zwm, equals: " + integer.equals(64));
    }

    public void testHashCode() {
        Log.d(TAG, "zwm, hashCode: " + integer.hashCode());
    }

    public void testByteValue() {
        byte value = integer.byteValue();
        Log.d(TAG, "zwm, byteValue: " + value);
    }

    public void testShortValue() {
        short value = integer.shortValue();
        Log.d(TAG, "zwm, shortValue: " + value);
    }

    public void testIntValue() {
        int value = integer.intValue();
        Log.d(TAG, "zwm, intValue: " + value);
    }

    public void testLongValue() {
        long value = integer.longValue();
        Log.d(TAG, "zwm, longValue: " + value);
    }

    public void testFloatValue() {
        float value = integer.floatValue();
        Log.d(TAG, "zwm, floatValue: " + value);
    }

    public void testDoubleValue() {
        double value = integer.doubleValue();
        Log.d(TAG, "zwm, doubleValue: " + value);
    }

    public void testCompareTo() {
        Log.d(TAG, "zwm, compareTo: " + integer.compareTo(66));
    }

    public void testToString() {
        Log.d(TAG, "zwm, toStrng: " + integer.toString());
    }

    public void test() {
        Integer a = new Integer(100); //在堆内存生成一个新对象
        Integer b = new Integer(100); //在堆内存生成一个新对象
        Log.d(TAG, "zwm, a == b: " + (a==b));

        Integer c = new Integer(100); //在堆内存生成一个新对象
        int d = 100; //基本数据类型
        Log.d(TAG, "zwm, c == d: " + (c==d)); //Integer与int进行比较时,Integer自动拆箱为int

        Integer e  = new Integer(100); //在堆内存生成一个新对象
        Integer f = 100; //Integer f = Integer.valueOf(100),在[-128,127]区间,返回IntegerCache缓存
        Log.d(TAG, "zwm, e == f: " + (e==f));

        Integer g = 100; //在[-128,127]区间,返回IntegerCache缓存
        Integer h = 100; //在[-128,127]区间,返回IntegerCache缓存
        Log.d(TAG, "zwm, g == h: " + (g==h));

        Integer i = 128; //不在[-128,127]区间,在堆内存生成一个新对象
        Integer j = 128; //不在[-128,127]区间,在堆内存生成一个新对象
        Log.d(TAG, "zwm, i == j: " + (i==j));
    }

    public void testStaticMethod() {
        Integer value = Integer.valueOf("123");
        Log.d(TAG, "zwm, valueOf 123: " + value);

        int value2 = Integer.parseInt("123");
        Log.d(TAG, "zwm, parseInt 123: " + value2);

        String str = Integer.toString(66);
        Log.d(TAG, "zwm, toString 66: " + str);

        String str2 = Integer.toBinaryString(66);
        Log.d(TAG, "zwm, toBinaryString 66: " + str2);

        String str3 = Integer.toOctalString(66);
        Log.d(TAG, "zwm, toOctalString 66: " + str3);

        String str4 = Integer.toHexString(66);
        Log.d(TAG, "zwm, toHexString 66: " + str4);
    }
}

//测试代码
private void testMethod() {
    Log.d(TAG, "zwm, testMethod");
    TestInteger testInteger = new TestInteger();
    testInteger.testEquals();
    testInteger.testHashCode();
    testInteger.testByteValue();
    testInteger.testShortValue();
    testInteger.testIntValue();
    testInteger.testLongValue();
    testInteger.testFloatValue();
    testInteger.testDoubleValue();
    testInteger.testCompareTo();
    testInteger.testToString();
    testInteger.test();
    testInteger.testStaticMethod();
}

//输出log
2019-08-21 11:45:23.025 zwm, testMethod
2019-08-21 11:45:23.026 zwm, equals: true
2019-08-21 11:45:23.026 zwm, hashCode: 64
2019-08-21 11:45:23.027 zwm, byteValue: 64
2019-08-21 11:45:23.027 zwm, shortValue: 64
2019-08-21 11:45:23.027 zwm, intValue: 64
2019-08-21 11:45:23.027 zwm, longValue: 64
2019-08-21 11:45:23.027 zwm, floatValue: 64.0
2019-08-21 11:45:23.027 zwm, doubleValue: 64.0
2019-08-21 11:45:23.028 zwm, compareTo: -1
2019-08-21 11:45:23.028 zwm, toStrng: 64
2019-08-21 11:45:23.028 zwm, a == b: false
2019-08-21 11:45:23.028 zwm, c == d: true
2019-08-21 11:45:23.028 zwm, e == f: false
2019-08-21 11:45:23.028 zwm, g == h: true
2019-08-21 11:45:23.028 zwm, i == j: false
2019-08-21 11:45:23.028 zwm, valueOf 123: 123
2019-08-21 11:45:23.029 zwm, parseInt 123: 123
2019-08-21 11:45:23.029 zwm, toString 66: 66
2019-08-21 11:45:23.029 zwm, toBinaryString 66: 1000010
2019-08-21 11:45:23.029 zwm, toOctalString 66: 102
2019-08-21 11:45:23.029 zwm, toHexString 66: 42

三、原理

重要参数

//用于实际存放数据
private final int value;

//最小值
public static final int   MIN_VALUE = 0x80000000;

//最大值
public static final int   MAX_VALUE = 0x7fffffff;

//表明Integer类为基本数据类型int的包装器类型
public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

构造函数

//指定一个int类型数据的构造函数
public Integer(int value) {
    this.value = value;
}

//指定一个字符串类型数据的构造函数
public Integer(String s) throws NumberFormatException {
    this.value = parseInt(s, 10);
}

public boolean equals(Object obj)

//比较基本类型数据是否相等
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

public static int hashCode(int value)

//返回基本类型数据
public static int hashCode(int value) {
    return value;
}

public int intValue()

//返回int型数据
public int intValue() {
    return value;
}

public byte byteValue()

//返回byte型数据
public byte byteValue() {
    return (byte)value;
}

public int compareTo(Integer anotherInteger)

//将当前Integer对象与指定的Integer对象进行比较
public int compareTo(Integer anotherInteger) {
    return compare(this.value, anotherInteger.value);
}

public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

public String toString()

//将Integer对象转成字符串对象
public String toString() {
    return toString(value);
}

public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(buf, true);
}

static int stringSize(int x) {
    for (int i=0; ; i++)
        if (x <= sizeTable[i])
            return i+1;
}

private static class IntegerCache

//缓存类
//在第一次被使用的时候进行初始化,可支持-128到127之间的自动装箱过程,最大值127可以通过JVM的启动参数-XX:AutoBoxCacheMax=size修改
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[]; //缓存数组

    static { //静态块
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++); //初始化缓存数组

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}

public static Integer valueOf(int i)

//将int型数据转成Integer对象
//如果在缓存范围内则返回缓存对象,否则创建新的Integer对象
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

public static int parseInt(String s)

//将字符串转成十进制int型数据
public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
}

public static String toBinaryString(int i)

//将int型数据转成二进制字符串
public static String toBinaryString(int i) {
    return toUnsignedString0(i, 1);
}

private static String toUnsignedString0(int val, int shift) {
    // assert shift > 0 && shift <=5 : "Illegal shift value";
    int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
    int chars = Math.max(((mag + (shift - 1)) / shift), 1);
    char[] buf = new char[chars]; //创建char型数组

    formatUnsignedInt(val, shift, buf, 0, chars);

    // Use special constructor which takes over "buf".
    return new String(buf, true);
    
public static int numberOfLeadingZeros(int i) {
    // HD, Figure 5-6
    if (i == 0)
        return 32;
    int n = 1;
    if (i >>> 16 == 0) { n += 16; i <<= 16; }
    if (i >>> 24 == 0) { n +=  8; i <<=  8; }
    if (i >>> 28 == 0) { n +=  4; i <<=  4; }
    if (i >>> 30 == 0) { n +=  2; i <<=  2; }
    n -= i >>> 31;
    return n;
}

static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
    int charPos = len;
    int radix = 1 << shift;
    int mask = radix - 1;
    do {
        buf[offset + --charPos] = Integer.digits[val & mask];
        val >>>= shift;
    } while (val != 0 && charPos > 0);

    return charPos;
}
上一篇 下一篇

猜你喜欢

热点阅读