我是泛型的新手,我不确定我的问题的答案是基于意见
还是有真正的理由。在下面的代码中,需要什么来区分对象条目的键?
Object k;
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
它似乎很容易被替换为
if (e.hash == hash && (e.key == key || (key != null && key.equals(e.key))))
更多引用:
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
最佳答案
这是一种极端的优化措施,对于通用编程实践来说可能不是必需的。这是一个 discussion那可以回答你的问题。以下声明是从该帖子中复制的:
It's a coding style made popular by Doug Lea. It's an extreme optimization that probably isn't necessary; you can expect the JIT to make the same optimizations. (you can try to check the machine code yourself!) Nevertheless, copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine.
关于java - 为什么要在 HashMap 中为 getEntry 定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19395003/