java package data type --Long

  Long encapsulation is long long integer data types. We know that long int is the relative difference in data representation range expanded, most of the other features are the same. So Long Integer with most of the methods are the same.

  Integer learning articles: https://www.cnblogs.com/coding-one/p/11387983.html

  Here are some differences in features:

 

1. caching mechanism

  Like type Integer, Long also provides a caching mechanism. It is not as long int larger than the range, Long range should be large than the Integer cache it? In fact, no. Long type and the configuration of maximum cancellation cache, the cache directly set the range [-128, 127].

    private static class LongCache {
        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);
        }
    }

 

2. hashCode() 值

  Integer 类型 hashCode 值就是它保存的 int 值,那么 Long 是否也是它所保存的 long 值呢?答案当然是否。因为根据常规约定,hashCode 值是一个 int 数值,long 型显然不合适,于是 Long 对其值做了处理,以得到一个 int 类型能够表示的值:

    public static int hashCode(long value) {
        return (int)(value ^ (value >>> 32));
    }

  可以看出,Long 将 值进行操作得到 hashCode:

    2.1. long 值 按位补零右移32位,此时得到的结果的高32位全部是0,而低32位则是原来的高32位;

    2.2. 将 2.1 中得到的结果与 long 值按位异或运算,此时得到的值的高32位与原 long 值的一样,低32位是原 long 值的高32位与低32位异或的结果;

    2.3. 将 2.2 中得到的 long 值结果强制转换成 int 型;

  上述步骤中最关键的就是 按位异或 了,强转之后,高位已经丢失,留下按位异或后的低位,这样就能得到相对散列的哈希值了。

 

  下面我们举一个缩小版的例子:

    约定:

      1. 使用一个字节类比 long 型,半个字节(4 bits)类比 int 型;

      2. 使用原码表示法;

      3. 无符号位;

    目的:将大于 15(4个bits能够表示的最大值)的数计算后得到 [0, 15](无符号原码 4 bits能够表示的范围)之间的数值。

    例子:248、43

      1. 上述两个数的无符号源码表示为:11111000、00101011

      2.分别补零右移4位得到:00001111、00000010

      3.右移前后按位异或得到:11110111、00101001

      4.丢弃高位后得到:0111、1001

      5.转换成数值为:7、9

  可以看到,在原码表示法下,原来使用 4个bit位表示不了的的两个数 248 和 43 ,通过一系列按位运算,现在散列在了 4 个 bit 能够表示的数值,目的达到了。

  注意:上述只是一个简单的类比的例子,实际计算机中计算的是补码,而且字节长度分别为 8 bytes 和 4 bytes。

  

    

 

Guess you like

Origin www.cnblogs.com/coding-one/p/11390317.html