具有空键和空值的哈希映射
2022-09-01 06:29:55
请考虑以下代码:
import java.util.*;
class Employee {
String name;
public Employee(String nm) {
this.name=nm;
}
}
public class HashMapKeyNullValue {
Employee e1;
public void display(){
Employee e2=null;
Map map=new HashMap();
map.put(e2, "25");
System.out.println("Getting the Value When e2 is set as KEY");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
map.put(e1, "");
System.out.println("Getting the Value when e1 is set as KEY");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
map.put(null, null); // null as key and null as value
System.out.println("Getting the Value when setting null as KEY and null as value");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
map.put(null, "30");
System.out.println("Getting the Value when setting only null as KEY");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
}
public static void main(String[] args) {
new HashMapKeyNullValue().display();
}
}
程序的输出为:
Getting the Value When e2 is set as KEY
e2 : 25
e1 : 25
null : 25
Getting the Value when e1 is set as KEY
e2 :
e1 :
null :
Getting the Value when setting null as KEY and null as value
e2 : null
e1 : null
null : null
Getting the Value when setting only null as KEY
e2 : 30
e1 : 30
null : 30
在这里,作为键是如何相互关联的。是否所有三者都分配给相同的哈希码?如果是,为什么?e1, e2, and null
由于这三者看起来都不同,因此一个值的变化会改变另一个值。这是否意味着,只有一个密钥条目被制作成任何一个?因为所有都被视为相同的密钥。HashMap
e1, e2 or null