小编典典

具有Null键和Null值的HashMap

java

考虑以下代码:

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


阅读 190

收藏
2020-10-20

共1个答案

小编典典

HashMap 当将 null 作为键传递并且null作为特殊情况处理时,不会调用哈希码。

放置方法

HashMapnull 键放在存储区 0中, 并将 null
作为键映射到传递的值。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方法中,检查key是否作为 null 传递。存储区 0 中空 键的搜索值。 __

因此,在一个中只能有一个空键 __hashmap 目的。

2020-10-20