HashMap with Null Key and Null Value

后端 未结 5 1531
一个人的身影
一个人的身影 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条回答
  •  一整个雨季
    2020-12-14 08:03

    HashMap does not call hashcode when null is passed as key and null Key is handled as special case.

    Put Method

    HashMap puts null key in bucket 0 and maps null as key to passed value. HashMap does it by linked list data structure. HashMap uses linked list data structure internally.

    Linked list data structure used by HashMap (a static class in HashMap.java)

    static class Entry implements Map.Entry {
            final K key;
            V value;
            Entry next;
            final int hash;
    }
    

    In Entry class the K is set to null and value mapped to value passed in put method.

    Get Method

    While in Hashmap get method the checks if key is passed as null. Search Value for null key in bucket 0.

    Hence there can only be one null key in one hashmap object.

提交回复
热议问题