HashMap with Null Key and Null Value

后端 未结 5 1536
一个人的身影
一个人的身影 2020-12-14 07:29

Consider the following Code :

import java.util.*;

class Employee {

    String name;

    public Employee(String nm) {
        this.name=nm;
    }
}

publ         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 08:20

    A HashMap can only store one value per key. If you want to store more values, you have to use a MultivalueHashMap (Google Guava and Apache Commons Collections contain implementations of such a map).

    e1 and e2 have the value null, since you don't assign any object to them. So if you use those variables, the key of that map entry is also null, which leads to your result. Null doesn't have any hashcode, but is tolerated as key in the HashMap (there are other Map implementations which don't allow Null as key).

提交回复
热议问题