Java8源码学习 - Integer

Integer 是 int 的包装类

public final class Integer extends Number implements Comparable<Integer>

Number这个类是所有java基本数据类型对应的包装类(不包括String)都必须继承的抽象父类,其中定义了各个类型转换的抽象方法。

Comparable这个接口是一个函数式接口,提供一个比较器

 @Native public static final int   MIN_VALUE = 0x80000000;

@Native public static final int   MAX_VALUE = 0x7fffffff;

定义Integer数值的阙值,其中@Native注解,是一个源文件级别的注解-即:仅在源文件中有效,不被编译进class文件,且只能用于类的成员变量上

/**

 * Indicates that a field defining a constant value may be referenced

 * from native code.

  表明定义常量值的字段可以从本机代码中引用。怎么引用?暂时不知道

 * @since 1.8
 */
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface Native {
}
/**
     * The {@code Class} instance representing the primitive type
     * {@code int}.
     *原始类型的实例  具体的使用情况?暂时不知道
     * @since   JDK1.1
     */
    @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'
    };//所有的表示一个数字的字符窜可能-36个
    public static String toString(int i, int radix) {
        //将字符窜以redix进制转换--先构造一个char数组用于存储,进制转换后的字符,r
        //如果基数不在一个字符应有的范围(2~36)则为10进制
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;
        /* Use the faster version */
       //如果为10进制不进行进制转换
        if (radix == 10) {
            return toString(i);
        }
          //进制转换
        char buf[] = new char[33];

为什么初始化大小为:33?

//当radix为2时:将i转换为2进制,最高位数32位

//int类型4个字节32位 虽然有一个符号位但可以直接参与运算

//比如:8

内存中是:(整数在内存中以补码的形式储存,整数的补码为其原码

   正数 00000000000000000000000000001000 负数 11111111111111111111111111111000

   不清楚的参考:http://www.cnblogs.com/zhangziqiu/archive/2011/03/30/ComputerCode.html

而我们主观的是正数(原码):

00000000000000000000000000001000     1000                                   

10000000000000000000000000001000  -1000

    这个符号并不存在内存中,需要程序自己处理的识别符号位然后自己添上符号,所以需要33位

    boolean negative = (i < 0);//判断整形i是否为负数,如果为负数,需要补符号
        int charPos = 32;
        if (!negative) {//此语句之后i的值必然为负数
            i = -i;
        }

为什么要把i的值变为负数再进行运算而不变为正数?

 最大的负数:MIN_VALUE = 0x80000000  

     -2147483648   10000000000000000000000000000000 ①

  最大的正数:MAX_VALUE = 0x7fffffff;  

     2147483647     01111111111111111111111111111111 ②

     -2147483647   11111111111111111111111111111111 ③

       观察①和③,发现:我艹,原本只相差1的两个负数,二进制差这么大,简直是两个极端

 Integer.MAX_VALUE - Integer.MIN_VALUE = -1  

 Integer.MIN_VALUE - Interger.MIN_VALUE = 1  

        最大-最小 = -1  最小 - 最大 = 1

 System.out.println(Integer.MAX_VALUE>Integer.MIN_VALUE);会是什么结果?true

 System.out.println(Integer.MAX_VALUE-Integer.MIN_VALUE>0);?false

  ==>有时候用相减来判断大小并不可靠, 在java中Number类型 (a>b) == (a-b>0)不是绝对正确的。。。。

 while (i <= -radix) {//将整形按基数一次拆分赋值
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        //最高位赋值
        buf[charPos] = digits[-i];
        if (negative) {//如果i为负数则添上符号位
            buf[--charPos] = '-';
        }
                  //返回String类型的新对象
        return new String(buf, charPos, (33 - charPos));
    }
public static String toUnsignedString(int i) {
        return Long.toString(toUnsignedLong(i));
}
public static String toUnsignedString(int i, int radix) {
       return Long.toUnsignedString(toUnsignedLong(i), radix);
 }

 为什么要借用Long的方法?

 无符号数和有符号数不同之处在于没有符号位,所以数值位无符号比有符号的多一位

Integer的 MIN_VALUE  和   MAX_VALUE是有符号位的,  自身的toString方法不能满足条件,所以需要借助64位的Long来转换 

      System.out.println(Integer.toString(2147483649));  MAX_VALUE = 0x7fffffff; 2147483647

编译不通过 

       Integer.toString(int i)==> 不支持除int类型的其他类型数据

判断是否在整形范围类实在编译阶段,自动装箱时候

 public static long toUnsignedLong(int x) {

        return ((long) x) & 0xffffffffL;

 }// &是运算,因为是无符号的,所以所有的数都当正数看,int转long时不需要在前面按符号填0或1,

都填0

System.out.println(Long.toUnsignedString(-8, 2));  

 1111111111111111111111111111111111111111111111111111111111111000

System.out.println(Long.toUnsignedString(-8&0xffffffffL, 2));

 11111111111111111111111111111000

对比:返回有符号的Long方法


public long longValue() {
        return (long)value;
 }

 返回无符号的String,差别是:正数无差别,此处只讨论输出情况

      Integer.toString(-8,2): -1000

      Integer.toUnsignedString(-8,2): 11111111111111111111111111111000

 toUnsignedString方法将按基数原样返回内存中储存的所有位数,不考虑符号位,int 32位(2进制)  Long 64位(2进制)

Long.toUnsignedString(-8,2):1111111111111111111111111111111111111111111111111111111111111000
public static String toHexString(int i) {
    return toUnsignedString0(i, 4);
}//以16进制的无符号整数形式返回一个字符串实例
toUnsignedString0() 不是 toUnsignedString()
public static String toOctalString(int i) {
        return toUnsignedString0(i, 3);
}//以8进制的无符号整数形式返回一个字符串实例
 public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
}//以2进制的无符号整数形式返回一个字符串实例
    返回整形在内存中二进制32位其数值最高位(左边)前面的零位的数量
    即:32-数值位
==》
   System.out.println(Integer.toUnsignedString(8,2)+":"+Integer.numberOfLeadingZeros(8));
   System.out.println(Integer.toUnsignedString(-8,2)+":"+Integer.numberOfLeadingZeros(8);
   result:
         1000:28
         11111111111111111111111111111000:28
    public static int numberOfLeadingZeros(int i) {
        // HD, Figure 5-6
        if (i == 0)
            return 32;
        int n = 1;
        //初始位数为1,因为I为int类型必有一个符号位,此方法用于toUnsignedString0方法
        if (i >>> 16 == 0) { n += 16; i <<= 16; }
        //右移16位为0 则表示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;
    }
   /**
     * Convert the integer to an unsigned number.
      这是一个私有的方法,内部的工具方法,不需要对外部开放
      int shift表示转换为(2的shift次方)位的数值字符形式
     */
    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);//mag为字符的长度
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);//数组的长度,最小为1
        char[] buf = new char[chars];
        formatUnsignedInt(val, shift, buf, 0, chars);//给buf字符数组赋值
        // Use special constructor which takes over "buf".
        return new String(buf, true);
    }
      /**
     * Format a long (treated as unsigned) into a character buffer.
     * @param val the unsigned int to format
     * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
     * @param buf the character buffer to write to
     * @param offset the offset in the destination buffer to start at
     * @param len the number of characters to write
     * @return the lowest character  location used
     */ 
     给buf字符数组赋值并返回其下标(最小),对外不可见,子类可见
     static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
        int charPos = len;//数组长度
        int radix = 1 << shift;//基数 --2 4 8 16
        int mask = radix - 1;
        do {
            buf[offset + --charPos] = Integer.digits[val & mask];
            val >>>= shift;
        } while (val != 0 && charPos > 0);
        return charPos;
    }
。。。

中间的一些string或基本类型转换的方法都比较好理解,略过。。。没有需要注意的地方


下面是一些integer对象的实例和自动装箱需要注意的方法等

 在源文件中:

   integer i = 12;

 编译后的class文件中:

   Integer i = Integer.valueOf(12);

这是一个自动装箱的过程,实际上调用的是Integer.valueOf(int i)这个方法,

拆箱调用的是 public int intValue()方法

 public static Integer valueOf(int i) {

        if (i >= IntegerCache.low && i <= IntegerCache.high)

            return IntegerCache.cache[i + (-IntegerCache.low)];

        return new Integer(i);

 }

它会将一个范围(low - high)的整型值赋给其私有内部类IntegerCache的一个数值cache的某个元素,然后从其中取出一个对象的引用返回

low 和 high 默认是-128 127    可以改变(仅int类型的整形可变,其他不可变)

所以整型的所有在此范围类的相同的值的引用指向的都是同一个对象

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

整形的hashcode返回的都是装换为Int类型后的值,int直接返回其值

public static int hashCode(int value) {
        return value;
 }
 public static int hashCode(long value) {
        return (int)(value ^ (value >>> 32));
     //高位与地位进行^运算。。目的?
      可以避免负数的存在
     System.out.println(Long.hashCode(-2L));
      System.out.println(Integer.hashCode((int)-2L));
      System.out.println(Integer.hashCode((int)-214788388898L));
       System.out.println(Long.hashCode(-214788388898L));
      ===》
         1
        -2
        -40024098
        40024083
     从上可以看出,此运算可以有效的避免Long转int舍去时符号位影响,是hashcode保持正数
     而且这样会让hashcode碰撞几率增大
       比如 40024083 和 -214788388898L的hashcode一样
     那么hashcode为负数又怎么样?
         暂时不知道?有知道的朋友还请告知。。。
 }
 public static int hashCode(byte value) {
        return (int)value;
 }
 public static int hashCode(short value) {
        return (int)value;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨中漫步t2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值