JDK1.8源码阅读(3)--Byte/Double/Float /Integer

JDK1.8源码阅读(3)–Byte/Double/Float /Integer

前面两章写的过于冗长,接下来会省略些简单的又不是很重要的方法,重点突出那些有阅读意义的代码。

一.Byte类

类图:在这里插入图片描述
继承于抽象类Number和接口Comparable
插播一个Number抽象类:
在这里插入图片描述
Number是数值类型包装类共同的祖先,声明了各种包装类型的拆箱方法。
在这里插入图片描述
成员变量是序列号。
接下是方法:都是以XX形式返回当前对象的值。
进入正题,Byte类:
Byte类也是一个包装类
其中包含的变量:
由于byte是8位的而且java中是有符号数,所以定义了byte所能表达的最大数和最小数
1.public static final byte MIN_VALUE = -128
2.public static final byte MAX_VALUE = 127
3.public static final Class TYPE = (Class) Class.getPrimitiveClass(“byte”);相当于byte.class
4.private final byte value储存对象的值
5.public static final int SIZE = 8;
6.public static final int BYTES = SIZE / Byte.SIZE 类型所占字节
7.private static final long serialVersionUID = -7183698231559129828L;序列号
方法:
1.public static String toString(byte b)
byte转String
2.private static class ByteCache
私有内部类, Byte缓存,缓存了-128~127之间的Byte对象

    private static class ByteCache {
        private ByteCache(){}

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

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }

3.public static Byte valueOf(byte b)装箱,根据byte值从cache中找出对应的Byte对象
4.public static byte parseByte(String s, int radix)
将字符串根据其进制转换成byte
5.public static byte parseByte(String s)
将字符串按默认10进制转换成byte
6.public static Byte valueOf(String s, int radix)
将字符串根据其进制转换成byte并装箱
7.public static Byte valueOf(String s)
将字符串按默认10进制转换成byte并装箱
8.public static Byte decode(String nm)
将字符串nm解析为byte,随后再装箱
采用哪种进制解析nm取决于nm的格式:

0x、0X、#开头,代表按16进制解析
0开头,代表按8进制解析
其他情形默认按10进制解析

    public static Byte decode(String nm) throws NumberFormatException {
        int i = Integer.decode(nm);
        if (i < MIN_VALUE || i > MAX_VALUE)
            throw new NumberFormatException(
                    "Value " + i + " out of range from input " + nm);
        return valueOf((byte)i);
    }

9.public Byte(byte value)
构造函数
10.public Byte(String s)
通过String构造函数
11.public byte byteValue()
12.public short shortValue()
13.public short intValue()
14.public short floatValue()
15.public short longValue()
16.public short doubleValue()
17.public String toString()调用的是Integer的toString方法
18.public int hashCode()
19.public static int hashCode(byte value),hashcode值就是int类型的对象值
20.public boolean equals(Object obj)
21.public int compareTo(Byte anotherByte)复写comparable
22.public static int compare(byte x, byte y) 外比较器
23.public static int toUnsignedInt(byte x) 将byte转成无符号的int值
24.public static long toUnsignedLong(byte x)

二.Double类

类图:
在这里插入图片描述
继承了抽象类Number和接口Comparable
成员变量:
1.public static final double POSITIVE_INFINITY = 1.0 / 0.0; 代表正无穷大
2.public static final double NEGATIVE_INFINITY = -1.0 / 0.0; 代表负无穷大
3.public static final double NaN = 0.0d / 0.0; 代表非数字
4.public static final double MAX_VALUE = 0x1.fffffffffffffP+1023 double最大数
5.public static final double MIN_NORMAL = 0x1.0p-1022 double最小正值
6.public static final double MIN_VALUE = 0x0.0000000000001P-1022 double最小数
7.public static final int MAX_EXPONENT = 1023 double二进制形式指数部分最大值
8.public static final int MIN_EXPONENT = -1022 double二进制形式指数部分最小值
9.public static final int SIZE = 64 Double所占的位数
10.public static final int BYTES = SIZE / Byte.SIZE; 当前类型所占字节
11.public static final Class TYPE = (Class) Class.getPrimitiveClass(“double”); double.class
12.private final double value 用来存放Double对象的值
方法:
1.public static String toString(double d) 将double转成字符串
2.public static String toHexString(double d) 将double转成16进制字符串

public static String toHexString(double d) {
//首先判断输入的d是不是无限的
        if (!isFinite(d) )
            // For infinity and NaN, use the decimal output.
            return Double.toString(d);
        else {
            // Initialized to maximum size of output.
            StringBuilder answer = new StringBuilder(24);
			//如果是负数的就把符号位加上
            if (Math.copySign(1.0, d) == -1.0)    // value is negative,
                answer.append("-");                  // so append sign info

            answer.append("0x");

            d = Math.abs(d);

            if(d == 0.0) {
                answer.append("0.0p0");
            } else {
                boolean subnormal = (d < DoubleConsts.MIN_NORMAL);

                // Isolate significand bits and OR in a high-order bit
                // so that the string representation has a known
                // length.
                long signifBits = (Double.doubleToLongBits(d)
                                   & DoubleConsts.SIGNIF_BIT_MASK) |
                    0x1000000000000000L;

                // Subnormal values have a 0 implicit bit; normal
                // values have a 1 implicit bit.
                answer.append(subnormal ? "0." : "1.");

                // Isolate the low-order 13 digits of the hex
                // representation.  If all the digits are zero,
                // replace with a single 0; otherwise, remove all
                // trailing zeros.
                String signif = Long.toHexString(signifBits).substring(3,16);
                answer.append(signif.equals("0000000000000") ? // 13 zeros
                              "0":
                              signif.replaceFirst("0{1,12}$", ""));

                answer.append('p');
                // If the value is subnormal, use the E_min exponent
                // value for double; otherwise, extract and report d's
                // exponent (the representation of a subnormal uses
                // E_min -1).
                answer.append(subnormal ?
                              DoubleConsts.MIN_EXPONENT:
                              Math.getExponent(d));
            }
            return answer.toString();
        }
    }

3.public static Double valueOf(String s)
将字符串转换成Double类型

    public static Double valueOf(String s) throws NumberFormatException {
        return new Double(parseDouble(s));
    }

4.public static Double valueOf(double d)装箱
5.public static double parseDouble(String s) 将字符串转换成double
6.public static boolean isNaN(double v) 判断当前double值是不是NaN
7.public static boolean isInfinite(double v) 判断double值是不是无限的
8.public static boolean isFinite(double d) 判断double值是不是有限的
9.public Double(double value) 构造函数
10.public Double(String s) 用字符串构造函数
11.public boolean isNaN() 判断当前对象是不是非数字
12.public boolean isInfinite() 判断当前对象是不是无限的
13.public String toString() 把当前对象转换成字符串
14.public byte byteValue() 把当前对象转成byte类型
15.public short shortValue() 把当前对象转成short类型
16.public int intValue()把当前对象转成int类型
17.public long longValue()把当前对象转成long类型
18.public float floatValue()把当前对象转成float类型
19.public double doubleValue()把当前对象转成double类型
20.public int hashCode() 返回当前对象的hashCode
21.public static int hashCode(double value)
生成对象的哈希码,先将double转换成long,然后把该long值向右移32位和原来的long进行异或处理

    public static int hashCode(double value) {
        long bits = doubleToLongBits(value);
        return (int)(bits ^ (bits >>> 32));
    }

22.public boolean equals(Object obj)首先判断obj是不是Double的实例,并且判断两者转换成long后的值是否相同
23.public static long doubleToLongBits(double value) 将double类型转换成long
先计算value的二进制格式,然后返回该二进制格式表示的long

    public static long doubleToLongBits(double value) {
        long result = doubleToRawLongBits(value);
        // Check for NaN based on values of bit fields, maximum
        // exponent and nonzero significand.
        if ( ((result & DoubleConsts.EXP_BIT_MASK) ==
              DoubleConsts.EXP_BIT_MASK) &&
             (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L)
            result = 0x7ff8000000000000L;
        return result;
    }

24.public static native long doubleToRawLongBits(double value)
用C++实现的方法,将value转成long
25.public static native double longBitsToDouble(long bits)
用C++实现的方法,将long转成double
26.public int compareTo(Double anotherDouble)
实现comparable接口的内比较器
27.public static int compare(double d1, double d2)
外比较器,需要注意的是double可能是NaN,需要分开讨论

    public static int compare(double d1, double d2) {
        if (d1 < d2)
            return -1;           // Neither val is NaN, thisVal is smaller
        if (d1 > d2)
            return 1;            // Neither val is NaN, thisVal is larger

        // Cannot use doubleToRawLongBits because of possibility of NaNs.
        long thisBits    = Double.doubleToLongBits(d1);
        long anotherBits = Double.doubleToLongBits(d2);

        return (thisBits == anotherBits ?  0 : // Values are equal
                (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
                 1));                          // (0.0, -0.0) or (NaN, !NaN)
    }

28.public static double sum(double a, double b) a+b
29.public static double max(double a, double b) 取最大值
30.public static double min(double a, double b) 取最小值
31.private static final long serialVersionUID = -9172774392245257468L; 序列号

三.Float类

类图:在这里插入图片描述
继承了抽象类Number,接口Comparable。
跟Double类中相似的成员变量和方法就不再赘述。

四.Integer类

在这里插入图片描述
Integer类继承于Number抽象类,Comparable接口
变量:@Native public static final int MIN_VALUE = 0x80000000; 底层实现
@Native public static final int MAX_VALUE = 0x7fffffff;
public static final Class TYPE = (Class) Class.getPrimitiveClass(“int”); Integer.class
final static char[] digits 进制计算时所用到的String
final static char [] DigitTens 十位数
final static char [] DigitOnes 个位数
final static int [] sizeTable 各个位数所能表达的最大十进制数集合
private final int value 储存对象的值
@Native public static final int SIZE = 32;
方法:
1.public static String toString(int i, int radix) 将int值按照进制转成String

    public static String toString(int i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        /* Use the faster version */
        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));
    }

2.public static String toUnsignedString(int i, int radix)
转成无正负的String,首先先将i看成没有符号位的long,然后将其转成没有符号位的String

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

3.public static String toHexString(int i)
将int值转成16进制后转变为String
4.public static String toOctalString(int i)
将int值转成8进制后转变为String
5.public static String toBinaryString(int i)
将int值转成2进制后转变为String
6.private static String toUnsignedString0(int val, int shift)
按2^shift进制返回val的无符号值

    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        //除了开头全是0后剩下的数的二进制位数
        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);
    }

7.static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len)
将无符号数val(10进制数)转成2^shift进制后存入字节数组buf中,返回的是buf数组中开头0的位数

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

8.public static String toString(int i)
将int转成String

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

9.public static String toUnsignedString(int i)
将无符号位的int值转成String
10.static void getChars(int int数据, int 开始指针, char[] 字符串数组)
将整数i中包含的符号转为byte存入buf

    static void getChars(int int数据, int 开始指针, char[] 字符串数组) {
        int 被截取后的数字, 截取的数字;
        int 字符串数组指针 = 开始指针;
        char 正负数标识 = 0;
      //提取符号位,并将i转换成正数
        if (int数据 < 0) {
            正负数标识 = '-';
            int数据 = -int数据;
        }
        // Generate two digits per iteration
        while (int数据 >= 65536) {//如果是16位到32位的int值			1234567
            被截取后的数字 = int数据 / 100;								//q=  12345
        // really: r = i - (q * 100);
            截取的数字 = int数据 - ((被截取后的数字 << 6) + (被截取后的数字 << 5) + (被截取后的数字 << 2));	//r=1234567-(12345*100) = 1234567-1234500=67;
            int数据 = 被截取后的数字;										//int数据=12345
            字符串数组 [--字符串数组指针] = DigitOnes[截取的数字];		//[][][][][][][7]
            字符串数组 [--字符串数组指针] = DigitTens[截取的数字];		//[][][][][][6][7]
        }
        // Fall thru to fast mode for smaller numbers
//         assert(int数据 <= 65536, int数据);
        //int数据=12345 
        for (;;) {
        	//12345-12340=5
        	//12345/10*10
        	//
            被截取后的数字 = (int数据 * 52429) >>> (16+3);	//12345/10
            //  0010 0110 1001 0100 0000 1001 1010 0101
            //	0000 0000 0000 0000 0000 0100 1101 0010 //100 0000 1001 1010 0101
            //	被截取后的数字 = 1234
            //  截取的数字 = 12345 - ((1234<<3)+(1234<<1))=12345-(9872+2468)=12345-12340=5
            截取的数字 = int数据 - ((被截取后的数字 << 3) + (被截取后的数字 << 1));  // r = i-(q*10) ...
            字符串数组 [--字符串数组指针] = digits [截取的数字];//[][][][][5][6][7]
            int数据 = 被截取后的数字;//int数据 = 1234
            if (int数据 == 0) break;
        }
        if (正负数标识 != 0) {
            字符串数组 [--字符串数组指针] = 正负数标识;
        }
    }

11.static int stringSize(int x)
表达int值所需要的String长度,为接下来生成String做准备

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

12.public static int parseInt(String s, int radix)
将String按照radix进制转成int。
13.public static int parseInt(String s)
将String按照10进制转成int。
14.public static int parseUnsignedInt(String s, int radix)
将String按照无符号位radix进制转成int。
15.public static int parseUnsignedInt(String s)
将String按照无符号位10进制转成int。
16.public static Integer valueOf(String s, int radix)
将String按照radix进制转成Integer。
17.public static Integer valueOf(String s)
将String按照10进制转成Integer。
18.private static class IntegerCache
Integer缓存,默认缓存了-128~127之间的Integer对象
如果想增加缓存数字的上限,比如将缓存范围改为[-128, 200],
则可以设置运行参数:
-XX:AutoBoxCacheMax=200
或 -Djava.lang.Integer.IntegerCache.high=200

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

19.public static Integer valueOf(int i) 装箱
20.public Integer(int value) 构造方法
21.public Integer(String s) 通过String来构造Integer
22.public byte byteValue() 以下都是拆箱方法
23.public byte shortValue()
24.public byte intValue()
25.public byte longValue()
26.public byte floatValue()
27.public byte doubleValue()
28.public String toString() 将当前对象转成字符串
29.public int hashCode() 返回哈希码
30.public static int hashCode(int value) Integer的哈希码就是自身value
31.public boolean equals(Object obj) 判等
32.public static Integer getInteger(String nm)
33.public static Integer getInteger(String nm, int val)

从系统属性中获取值,然后再装箱
其中,nm为某个系统属性,val为备用值
比如:
System.setProperty(“age”, “20”);
Integer x = getInteger(“age”, 25);
如果属性age存在(被提前设置),x的值为20。
如果属性age不存在,则x的值为备用值25。

34.public static Integer getInteger(String nm, Integer val)
35.public static Integer decode(String nm)
将字符串按规定进制解析成int后装箱。
规定进制看nm的开头,例如0x代表16进制,0代表8进制等等。
36.public int compareTo(Integer anotherInteger)
复写Comparable接口
37.public static int compare(int x, int y) 外比较器
38.public static int compareUnsigned(int x, int y)以无符号形式比较两个int。
39.public static long toUnsignedLong(int x) 将int值转成无符号的long
40.public static int divideUnsigned(int dividend, int divisor) 无符号形式进行除法
41.public static int remainderUnsigned(int dividend, int divisor) 无符号形式进行余数计算
42.public static int highestOneBit(int i) // 返回二进制位中开头首次出现的1所占的数位,比如00110100,返回32
43.public static int lowestOneBit(int i) 返回二进制位中结尾首次出现的1所占的数位,比如00110100,返回4
44.public static int numberOfLeadingZeros(int i) 开头处有多少个0
45.public static int numberOfTrailingZeros(int i) 结尾处有多少个0
46.public static int bitCount(int i) 字节位为1的个数
47.public static int rotateLeft(int i, int distance) 将i中的bit循环左移distance位
48.public static int rotateRight(int i, int distance)将i中的bit循环右移distance位
49.public static int reverse(int i) 将int值反转
50.public static int signum(int i) 判断i的正负。遇到负数返回-1,正数返回1,0返回0
51.public static int reverseBytes(int i) 以bit为单位逆置bit顺序
52.public static int sum(int a, int b)
53.public static int max(int a, int b)
54.public static int min(int a, int b)
55.@Native private static final long serialVersionUID = 1360826667806852920L; 序列号

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值