我以为的源码---Integer

           我只坚持做我以为对的事,走进源码,理解不对的地方欢迎指正。

Integer平时写代码一直在用,今天静下心来看看源码.


当前JDK版本为1.8.0;

除了Integer ,另外的基本类型的包装类都是final修饰的,不可被继承的类;


先来看看类里面的属性


一:属性


1.MIN_VALUE :

@Native public static final int   MIN_VALUE = 0x80000000;
   这个值是补码表示的int的最小值,即规定的-2147483648 ( 如果我没记错的话);

2.MAX_VALUE:

@Native public static final int   MAX_VALUE = 0x7fffffff;

3.TYPE:

 public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

这个属性从来没见过,字面上是Integer类的属性,通过该方法可以得到"int"的class对象?


4.value:显然就是Integer对象的值

 private final int value;

5..digits:注释是所有可能代表整数的字符,具体应该后面会用到?


6..其他的类似DigtalTens ,DigitOnes ,sizeTable 代码里看到哪里用了 我在记录;



二:构造方法

 1.传入一个int型变量,这个应该显而易懂

  2.

 查看parseInt(s,10)方法:

 public static int parseInt(String s, int radix)       //radix为基数;
                throws NumberFormatException
    {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }
       int result = 0;
        boolean negative = false;         //是否为负数的标志位
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);       //字符0  对应48    -号对应 45   +号对应43
            if (firstChar < '0') { 
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;  
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
   
              if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }

三:常见方法见面

1.  intValue:即返回value属性即Integer的值

public int intValue() {
        return value;
    }

类似的几个方法longValue、floatValue、doubleValue、shortValue、byteValue就是强制转换一下类型


2.valueOf:说到这个方法之前,我们先来看个东西;

private static class IntegerCache {     //静态内部类   IntegerCache
        static final int low = -128;      //最小值-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++);   //cache中的元素从-128至127

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

        private IntegerCache() {}
    }                   
在程序中第一次使用 Integer 的时候也需要一定的额外时间来初始化这个缓存。

具体细节我暂时还搞不懂,最后一句注释告诉我们 -128,127必须入池了;

此时回头看

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
可以明白  valueOf(int i)返回的对象如果如在-128至127之间 那么返回一个缓存池中对应的Integer对象;如果在范围之外,那new一个新的对象返回;下面我实验一下:



结果:


这是:在 Java 5 中,为 Integer 的操作引入了一个新的特性,用来节省内存和提高性能。整型对象在内部实现中通过使用相同的对象引用实现了缓存和重用

具体原因通过查阅得知:以下摘自:http://www.importnew.com/18884.html

这种 Integer 缓存策略仅在自动装箱(autoboxing)的时候有用,使用构造器创建的 Integer 对象不能被缓存。

Java 编译器把原始类型自动转换为封装类的过程称为自动装箱(autoboxing),这相当于调用 valueOf 方法


3.hashCode、hashCode(int value)

值得看一眼的是int类型的hashCode就是value值;





4.decode函数

public static Integer decode(String nm) throws NumberFormatException {
        int radix = 10;
        int index = 0;
        boolean negative = false;
        Integer result;

        if (nm.length() == 0)
            throw new NumberFormatException("Zero length string");
        char firstChar = nm.charAt(0);
        // Handle sign, if present
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;

        // Handle radix specifier, if present
        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        }
        else if (nm.startsWith("#", index)) {
            index ++;
            radix = 16;
        }
        else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
            index ++;
            radix = 8;
        }

        if (nm.startsWith("-", index) || nm.startsWith("+", index))
            throw new NumberFormatException("Sign character in wrong position");

        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Integer.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }

deocde的作用应该是将一个字符串解码为一个Integer对象返回;看到这里才发现radix也就是进制的意思;


暂且先看这么多,记着

走进源码,理解不对的地方欢迎指正。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值