Java基础学习之Integer学习

Java基础之Integer源码分析

Java基础学习之Integer学习

最近准备好好学习java,所以对学习过程做一个记录,首次学习自然有许多不懂的地方,希望能得到各位大牛的批评指正,
Integer,Long 和Short,Byte分别是int,long,short,byte等整型的包装类型,有各自的应用场景,其中int最常用,所以将Integer单独作为一篇学习,其余的类中的方法差别不大。

类的定义

Integer 是用 final 声明的常量类,不能被任何类所继承。并且 Integer 类继承了 Number 类和实现了 Comparable 接口。 Number 类是一个抽象类,8中基本数据类型的包装类除了Character 和 Boolean 没有继承该类外,剩下的都继承了 Number 类,该类的方法用于各种数据类型的转换,Comparable 接口就一个 compareTo 方法,用于元素之间的大小比较。

public final class Integer extends Number implements Comparable<Integer>

构造方法

  public Integer(int value) {
        this.value = value;
    }
    public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }

静态成员变量

//int 的最小值 -2^31
@Native public static final int   MIN_VALUE = 0x80000000;
//int的最大值
@Native public static final int   MAX_VALUE = 0x7fffffff;
//用于表示二进制形式的int的字节数,Byte.SIZE=8
public static final int BYTES = SIZE / Byte.SIZE;
//用于表示二进制形式的int的位数
@Native public static final int SIZE = 32;
//??
@SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
    //所有可能表示数字的字符
    final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };

常用方法

toString

1,toString方法,返回表示输入对应进制的数字的字符串表示

public static String toString(int i, int radix) {
//如果指定进制小于Character.MIN_RADIX=2或者大于
//Character.MAX_RADIX=36,则默认为10进制,
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        /* Use the faster version */
        //返回10进制toString方法
        if (radix == 10) {
            return toString(i);
        }
      //进制的转换操作
        char buf[] = new char[33];
        boolean negative = (i < 0);
        int charPos = 32;
   
        if (!negative) {
            i = -i;
        }
     //为啥用负值计算这里没搞明白?
        while (i <= -radix) {
        //每计算一次余数就放在字符数组最末尾
            buf[charPos--] = digits[-(i % radix)];
            //计算下一位
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }

默认10进制的toString方法,其中getChars方法对10进制做了特殊的优化

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);
    }

2,toUnsignedString0 将Integer转成无符号字符串,被内部方法调用,
做各种进制的字符串转换

 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];

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

        // Use special constructor which takes over "buf".
        return new String(buf, true);
    }
    //转换成16进制字符串
    public static String toHexString(int i) {
        return toUnsignedString0(i, 4);
    }
    //转换成8进制字符串
    public static String toOctalString(int i) {
        return toUnsignedString0(i, 3);
    }
    //转换成2进制字符串
    public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }

直接转成无符号字符串的方法是调用Long类的静态方法

public static String toUnsignedString(int i, int radix) {
        return Long.toUnsignedString(toUnsignedLong(i), radix);
    }
    //
     public static String toUnsignedString(int i) {
        return Long.toString(toUnsignedLong(i));
    }

parseInt

根据指定的进制将字符串转为有符号Integer

public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */
         
        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);
            //判断第一位字符是正或负
            if (firstChar < '0') { // Possible leading "+" or "-"
                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
                //调用Character.digit方法计算值
                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;
    }

直接返回Integer的方法,默认10进制

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

转为无符号数字的方法

public static int parseUnsignedInt(String s, int radix)
                throws NumberFormatException {
        if (s == null)  {
            throw new NumberFormatException("null");
        }

        int len = s.length();
        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar == '-') {
                throw new
                    NumberFormatException(String.format("Illegal leading minus sign " +
                                                       "on unsigned string %s.", s));
            } else {
                if (len <= 5 ||      // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
                    (radix == 10 && len <= 9) ) {      // Integer.MAX_VALUE in base 10 is 10 digits
                    return parseInt(s, radix);
                } else {
                    long ell = Long.parseLong(s, radix);
                    if ((ell & 0xffff_ffff_0000_0000L) == 0) {
                        return (int) ell;
                    } else {
                        throw new
                            NumberFormatException(String.format("String value %s exceeds " +
                                                                "range of unsigned int.", s));
                    }
                }
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }
    //10进制的转换方法
    public static int parseUnsignedInt(String s) throws NumberFormatException {
        return parseUnsignedInt(s, 10);
    }

valueOf:装箱

装箱过程:将基本数据类型转换为Integer对象
特别注意将范围在[-128,127]中时是返回一个已经存在的对象,而不是new一个对象,
对于其他整型的包装类型,Long,Short,Byte的valueOf方法实现类似,都有一个缓存。

//将字符串转换为Integer对象
public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }

    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }
//将Int转换为Integer对象
public static Integer valueOf(int i) {
          //当i 在[-128,127],不会创建新的对象,直接使用缓存中的对象
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

内部类 IntegerCache 缓存了-128到127 Integer对象

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() {}
    }

intValue:拆箱

直接返回整型

private final int value;
public int intValue() {
        return value;
    }

hashCode

返回值就是当前值

public int hashCode() {
        return Integer.hashCode(value);
    }
public static int hashCode(int value) {
        return value;
    }

equals

先装箱再拆箱比较

 public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

getInteger

获取系统属性值并转为Integer 对象,如果没有对应的属性值则返回null

public static Integer getInteger(String nm) {
        return getInteger(nm, null);
    }
     public static Integer getInteger(String nm, int val) {
        Integer result = getInteger(nm, null);
        return (result == null) ? Integer.valueOf(val) : result;
    }
public static Integer getInteger(String nm, Integer val) {
        String v = null;
        try {
            v = System.getProperty(nm);
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        if (v != null) {
            try {
                return Integer.decode(v);
            } catch (NumberFormatException e) {
            }
        }
        return val;
    }

compareTo

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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值