Hash
散列,哈希:把任意长度的输入通过一种算法(散列),变换成为固定长度的输出,这个输出值就是散列值。属于压缩映射,容易产生哈希冲突。Hash算法有直接取余法等。
产生哈希冲突时解决办法:开放寻址;2、再散列;3、链地址法(相同hash值的元素用链表串起来)。
ConcurrentHashMap在发生hash冲突时采用了链地址法。
md4,md5,sha-hash算法也属于hash算法,又称摘要算法。
位运算
int类型的位
高位 低位
31 | 30 | 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 | 4 | 3 | 2 | 1 | 0 |
0 | 0 | 0 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 | 0 | 1 | 0 | 0 | 0 |
2的0次方 = 1,2的1次方=2…….,以上表格代表数字 (2的5次方+2的3次方)= 40
由上面的表格可以看出,数字类型在数字渐渐变大时,是由低位慢慢向高位扩展的。
Java实际保存int型时 正数 第31位 =0 负数:第31位=1
常用位运算有:
- 位与 & (1&1=1 1&0=0 0&0=0)
- 位或 | (1|1=1 1|0=1 0|0=0)
-
位非 ~ ( ~1=0 ~0=1)
-
位异或 ^ (1^1=0 1^0=1 0^0=0)
- <<有符号左移 >>有符号的右移 >>>无符号右移 例如:8 << 2 = 32 8>>2 = 2
>>表示右移,如果该数为正,则高位补0,若为负数,则高位补1;
>>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0。
左移没有<<<运算符!
取模的操作 a % (Math.pow(2,n)) 等价于 a&( Math.pow(2,n)-1),一个数字取模于2的n次方=a&2的n次方-1
代码实现:
package com.caojiulu;
import java.io.UnsupportedEncodingException;
/**
*@author caojiulu
*
*类说明:演示位运算
*/
public class IntToBinary {
public static void main(String[] args) throws UnsupportedEncodingException {
int data = 4;
System.out.println("the 4 is "+Integer.toBinaryString(data));
//位与 &(1&1=1 1&0=0 0&0=0)
System.out.println("the 4 is "+Integer.toBinaryString(4));
System.out.println("the -4 is "+Integer.toBinaryString(-4));
System.out.println("the 6 is "+Integer.toBinaryString(6));
System.out.println("the 4&6 is "+Integer.toBinaryString(4&6));
//位或 | (1|1=1 1|0=1 0|0=0)
System.out.println("the 4|6 is "+Integer.toBinaryString(4|6));
//位非~(~1=0 ~0=1)
System.out.println("the ~4 is "+Integer.toBinaryString(~4));
//位异或 ^ (1^1=0 1^0=1 0^0=0)
System.out.println("the 4^6 is "+Integer.toBinaryString(4^6));
// <<有符号左移 >>有符号的右移 >>>无符号右移
System.out.println("the -4 is >>>"+Integer.toBinaryString(-4>>>8));
// <<有符号左移 >>有符号的右移 >>>无符号右移
System.out.println("the -4 is >>"+Integer.toBinaryString(-4>>8));
//取模的操作 a % (2^n) 等价于 a&(2^n-1)
System.out.println("the 345 % 16 is "+(345%16)+ " or "+(345&(16-1)));
}
}
运行结果:
the 4 is 100
the 4 is 100
the -4 is 11111111111111111111111111111100
the 6 is 110
the 4&6 is 100
the 4|6 is 110
the ~4 is 11111111111111111111111111111011
the 4^6 is 10
the -4 is >>>111111111111111111111111
the -4 is >>11111111111111111111111111111111
the 345 % 16 is 9 or 9