HashMap mit Null-Taste und der Null-Wert

Betrachten Sie den folgenden Code :

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

    }
}

Die Ausgabe des Programms ist :

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

Hier, wie e1, e2, and null als Schlüssel miteinander verbunden sind. Alle drei sind zugeordnet gleichen hashcode ? Wenn ja, WARUM ?

Da alle drei zu sein scheint, anders Aussehen, die änderung eines Wertes ändert sich die andere. Bedeutet es, dass nur ein Eintrag für den Schlüssel ist in HashMap entweder e1, e2, or null weil alle behandelt werden wie die gleichen Schlüssel.

Die Werte von e1 und e2 sind null. Java ist pass-by-value und pass wird nur der Wert einer variable, wenn diese variable wird als Aufruf-parameter. Das ist die variable, die werden niemals neu zugewiesen werden, innerhalb der Funktion und den Namen der parameter in der Funktion haben nichts zu tun mit irgendwelchen Variablen.
mögliche Duplikate von HashMap mit null als Schlüssel

InformationsquelleAutor Nizam | 2014-09-19

Schreibe einen Kommentar