java源码分析(11)-Long

本文深入解析 Java 中 Long 类的功能和内部实现,包括数值表示、字符串转换、数值解析、比较操作等核心方法。同时介绍了 Long 类的常用静态方法,如进制转换、位操作等,并解释了 Long 缓存机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public final class Long extends Number implements Comparable<Long> {
    public static final long MIN_VALUE = 0x8000000000000000L;//最大值为-2^63
    public static final long MAX_VALUE = 0x7fffffffffffffffL;//最小值为2^63-1
    public static final Class<Long>     TYPE = (Class<Long>) Class.getPrimitiveClass("long");
    public static String toString(long i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;//Long中进制数出错时,不跑异常,而是默认为10进制
        if (radix == 10)
            return toString(i);
        char[] buf = new char[65];
        int charPos = 64;
        boolean negative = (i < 0);

        if (!negative) {//统一转换为负数进行操作
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = Integer.digits[(int)(-(i % radix))];
            i = i / radix;
        }
        buf[charPos] = Integer.digits[(int)(-i)];

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

        return new String(buf, charPos, (65 - charPos));
    }
    public static String toHexString(long i) {//将Long转为16进制
        return toUnsignedString(i, 4);
    }
    public static String toOctalString(long i) {//将Long转为8进制
        return toUnsignedString(i, 3);
    }
    public static String toBinaryString(long i) {//将Long转为2进制
        return toUnsignedString(i, 1);
    }
    private static String toUnsignedString(long i, int shift) {
        char[] buf = new char[64];
        int charPos = 64;
        int radix = 1 << shift;
        long mask = radix - 1;
        do {
            buf[--charPos] = Integer.digits[(int)(i & mask)];//确定最后一位在进制中对应的值
            i >>>= shift;//右移赋值
        } while (i != 0);
        return new String(buf, charPos, (64 - charPos));
    }
    public static String toString(long i) {//与Integer的toString方法相同
        if (i == Long.MIN_VALUE)
            return "-9223372036854775808";//最小值特殊处理
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);//负数需要多一位用来放负号
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf, true);
    }
    static void getChars(long i, int index, char[] buf) {//使用了与Integer相同的getChars方法,不再分析
        long q;
        int r;
        int charPos = index;
        char sign = 0;

        if (i < 0) {
            sign = '-';
            i = -i;
        }

        // Get 2 digits/iteration using longs until quotient fits into an int
        while (i > Integer.MAX_VALUE) {
            q = i / 100;
            // really: r = i - (q * 100);
            r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
            i = q;
            buf[--charPos] = Integer.DigitOnes[r];
            buf[--charPos] = Integer.DigitTens[r];
        }

        // Get 2 digits/iteration using ints
        int q2;
        int i2 = (int)i;
        while (i2 >= 65536) {
            q2 = i2 / 100;
            // really: r = i2 - (q * 100);
            r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
            i2 = q2;
            buf[--charPos] = Integer.DigitOnes[r];
            buf[--charPos] = Integer.DigitTens[r];
        }

        // Fall thru to fast mode for smaller numbers
        // assert(i2 <= 65536, i2);
        for (;;) {
            q2 = (i2 * 52429) >>> (16+3);
            r = i2 - ((q2 << 3) + (q2 << 1));  // r = i2-(q2*10) ...
            buf[--charPos] = Integer.digits[r];
            i2 = q2;
            if (i2 == 0) break;
        }
        if (sign != 0) {
            buf[--charPos] = sign;
        }
    }
    static int stringSize(long x) {//展示Long的字符串长度
        long p = 10;
        for (int i=1; i<19; i++) {每次乘十进行比较
            if (x < p)
                return i;
            p = 10*p;
        }
        return 19;
    }
    public static long parseLong(String s, int 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");
        }

        long result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        long limit = -Long.MAX_VALUE;
        long multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Long.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;
    }
    public static long parseLong(String s) throws NumberFormatException {//默认转成10进制
        return parseLong(s, 10);
    }
    public static Long valueOf(String s, int radix) throws NumberFormatException {
        return Long.valueOf(parseLong(s, radix));
    }
    public static Long valueOf(String s) throws NumberFormatException
    {
        return Long.valueOf(parseLong(s, 10));
    }

    private static class LongCache {//Long的默认缓存,-128~127,缓存模块与Integer相同
        private LongCache(){}

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

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }
    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { //在缓存范围内则自动使用缓存中的值
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }
    public static Long decode(String nm) throws NumberFormatException {//用于对未知进制的long型字符串进行解码,根据开头的进制符判断进制,再转换为Long
        int radix = 10;
        int index = 0;
        boolean negative = false;
        Long 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 = Long.valueOf(nm.substring(index), radix);
            result = negative ? Long.valueOf(-result.longValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Long.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 = Long.valueOf(constant, radix);
        }
        return result;
    }
    private final long value;
    public Long(long value) {
        this.value = value;
    }
    public Long(String s) throws NumberFormatException {
        this.value = parseLong(s, 10);
    }
    public byte byteValue() {
        return (byte)value;
    }
    public short shortValue() {
        return (short)value;
    }
    public int intValue() {
        return (int)value;
    }
    public long longValue() {
        return (long)value;
    }
    public float floatValue() {
        return (float)value;
    }
    public double doubleValue() {
        return (double)value;
    }
    public String toString() {
        return toString(value);
    }
    public int hashCode() {//重写hashcode()方法,无符号右移32位后乘value本身
        return (int)(value ^ (value >>> 32));
    }
    public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();//比较的是value的地址值,所以在缓存范围内的相等,缓存范围外的不等(两个对象指向同一个Long除外)
        }
        return false;
    }
    public static Long getLong(String nm) {//用于获取系统变量
        return getLong(nm, null);
    }
    public static Long getLong(String nm, long val) {
        Long result = Long.getLong(nm, null);
        return (result == null) ? Long.valueOf(val) : result;
    }
    public static Long getLong(String nm, Long val) {
        String v = null;
        try {
            v = System.getProperty(nm);
        } catch (IllegalArgumentException e) {
        } catch (NullPointerException e) {
        }
        if (v != null) {
            try {
                return Long.decode(v);
            } catch (NumberFormatException e) {
            }
        }
        return val;
    }
    public int compareTo(Long anotherLong) {//由于实现了Comparable<Long>接口,所以需要实现compareTo方法
        return compare(this.value, anotherLong.value);
    }
    public static int compare(long x, long y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
    public static final int SIZE = 64;
    public static long highestOneBit(long i) {//返回二进制最高位的1的值
        // HD, Figure 3-1
        i |= (i >>  1);//Long为64位,所以要右移1,2,4,8,16,32,得到一个连续0和连续1组成的二进制数
        i |= (i >>  2);
        i |= (i >>  4);
        i |= (i >>  8);
        i |= (i >> 16);
        i |= (i >> 32);
        return i - (i >>> 1);//i减去i>>>1,即只剩下i的最高位的1(i由两部分组成,前面全为0,后面全为1)
    }
    public static long lowestOneBit(long i) {//将i转为2进制返回最右边的1所对应的10进制数,如1100返回4,1000返回8
        // HD, Section 2-1
        return i & -i;
    }
    public static int numberOfLeadingZeros(long i) {//返回i的开头的0的个数
        // HD, Figure 5-6
         if (i == 0)
            return 64;
        int n = 1;
        int x = (int)(i >>> 32);
        if (x == 0) { n += 32; x = (int)i; }
        if (x >>> 16 == 0) { n += 16; x <<= 16; }
        if (x >>> 24 == 0) { n +=  8; x <<=  8; }
        if (x >>> 28 == 0) { n +=  4; x <<=  4; }
        if (x >>> 30 == 0) { n +=  2; x <<=  2; }
        n -= x >>> 31;
        return n;
    }
    public static int numberOfTrailingZeros(long i) {//最右边开始数,有几个连续的0
        // HD, Figure 5-14
        int x, y;
        if (i == 0) return 64;
        int n = 63;
        y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
        y = x <<16; if (y != 0) { n = n -16; x = y; }
        y = x << 8; if (y != 0) { n = n - 8; x = y; }
        y = x << 4; if (y != 0) { n = n - 4; x = y; }
        y = x << 2; if (y != 0) { n = n - 2; x = y; }
        return n - ((x << 1) >>> 31);
    }
     public static int bitCount(long i) {//将i转化为二进制,返回二进制数中1的个数
        // HD, Figure 5-14
        i = i - ((i >>> 1) & 0x5555555555555555L);
        i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
        i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
        i = i + (i >>> 8);
        i = i + (i >>> 16);
        i = i + (i >>> 32);
        return (int)i & 0x7f;
     }
    public static long rotateLeft(long i, int distance) {//左旋转i值,比如i=110011,distance=1,返回100111
        return (i << distance) | (i >>> -distance);
    }
    public static long rotateRight(long i, int distance) {//右旋转i值,原理同上
        return (i >>> distance) | (i << -distance);
    }
    public static long reverse(long i) {//全部反转
        // HD, Figure 7-1
        i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
        i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
        i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
        i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
        i = (i << 48) | ((i & 0xffff0000L) << 16) |
            ((i >>> 16) & 0xffff0000L) | (i >>> 48);
        return i;
    }
    public static int signum(long i) {用于判断正负值
        // HD, Section 2-7
        return (int) ((i >> 63) | (-i >>> 63));
    }
    public static long reverseBytes(long i) {//将一个字节作为单位(8位)反转i,
        i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
        return (i << 48) | ((i & 0xffff0000L) << 16) |
            ((i >>> 16) & 0xffff0000L) | (i >>> 48);
    }
    private static final long serialVersionUID = 4290774380558885855L;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值