具有空键和空值的HashMap

Niz*_*zam 16 java collections null hashmap hashcode

请考虑以下代码:

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();

    }
}
Run Code Online (Sandbox Code Playgroud)

计划的输出是:

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
Run Code Online (Sandbox Code Playgroud)

这里e1, e2, and null键如何相互关联.是否所有三个都分配给相同的哈希码?如果是,为什么?

由于所有三个看起来都不同,一个值的变化会改变另一个.这是否意味着只有一个密钥条目被生成HashMap ,e1, e2, or null因为所有条目都被视为相同的密钥.

小智 39

HashMapnull作为键传递时,不调用hashcode,并且将null作为特殊情况处理.

放方法

HashMap斗关键0和地图的关键传递价值.HashMap通过链表数据结构来完成它.HashMap在内部使用链表数据结构.

HashMap(静态类HashMap.java)使用的链表数据结构

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;
}
Run Code Online (Sandbox Code Playgroud)

在Entry类中,K设置为null,值映射到put方法中传递的值.

获取方法

Hashmapget方法中,检查key是否作为null传递.在存储桶0中搜索null键的.

因此,一个中只能有一个空键 hashmap 宾语.

  • 仅供参考,答案是完全正确的,但是自 java 1.8 以来,HashMap 的实现略有变化。可以使用平衡树代替链表作为“桶” (3认同)
  • [PLUS ONE]清楚的解释和良好的例证 (2认同)

Kam*_*łys 6

如果您null作为地图键传递,它将转到0 bucket.null键的所有值都将在那里.这就是为什么它返回相同的值,导致您提供的所有键null都在HashMap的同一个桶中.

  • @dineshkandpal 是的,总是最后一个 (v2) (2认同)