【发布时间】:2021-04-14 20:25:12
【问题描述】:
考虑一下我从 JDK 的 LinkedList 类中找到的这段代码。
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
第一个问题:为什么在这段代码中声明了这个看似多余的局部变量l?据我所知,我们可以简单地使用last。
在 HashMap 类的下一个代码中,完成了同样的事情。局部变量tab被声明为等于实例变量table。
第二个问题:为什么final 没有在这里与tab 一起使用,就像在之前的代码中使用的那样?
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
【问题讨论】:
-
我认为这是为了线程安全,因此在 null 检查和返回之间不会发生写入。地图代码的of子句中也有赋值。
-
这很有意义。但是为什么
tab没有声明final呢? -
请不要在一个...问题中提出多个问题。
标签: java oop final instance-variables local-variables