具有空键和空值的 HashMap

新手上路,请多包涵

考虑以下代码:

 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 ?因为所有都被视为相同的密钥。

原文由 Nizam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 708
2 个回答

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

放置方法

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;
}

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

获取方法

Hashmap get 方法中,检查密钥是否作为 null 传递。存储桶 0 中空 键的搜索值。

因此,一个 hashmap 对象 中只能有一个空键

原文由 Sandeep Vaid 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 Kamil Kłys 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题