- ArrayDeque
public int size() {
return (tail - head) & (elements.length - 1);
}
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
上面运算就是为了代替取模,使用位运算效率更高
- HashMap
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
int32位,前16和后16异或运算,一是为了加上高16位的参与。二是异或运算相对于&和|(与和或)更加随机,因为0和1的概率都是50%,二与和或是75%–25%,能够相对减少hash至的冲突。