在阅读源代码时HashMap
,我遇到了以下代码public V put(K key, V value)
:
for (Entrye = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } }
为什么分配e.key
到k
比较?为什么不直接比较,如:
if (e.hash == hash && (e.key == key || key.equals(e.key))
-------------------更新------------------------
根据@seand的回答,我做了更详细的调查:
import com.test.Test; public class Main { public static void main(String[] args) { Test t = new Test(); int a = t.a; int b = a; } }
class test有一个int提交了一个;
使用javap -c Main获取类文件内容:
public static void main(java.lang.String[]); Code: 0: new #2 // class test/Test 3: dup 4: invokespecial #3 // Method test/Test."":()V 7: astore_1 8: aload_1 9: getfield #4 // Field test/Test.a:I 12: istore_2 13: iload_2 14: istore_3 15: return
int a = t.a
代表
8:[load the t object] 9:[access the field a] 12:[store the value to a]
参考jvm规范获取[getfield]的信息
int b = a
代表:
13:[load the local variable] 14:[store the value to b];
访问局部变量而不是类字段似乎是合理的.