简体   繁体   中英

Why does my hash map code print null?

I have the following code and I want to print x , y , and z . When I do that, I expect (1969, 21, 7) , (1969, 4, 12) , and (1969, 21, 7) respectively. Instead, I get null null null .

My question is, why does the code below print null for x, y, and z instead of the actual date?

import java.util.HashMap;
import java.util.GregorianCalendar;

public class GregorianCalenderTest {

    public static void main(String[] args) {

        HashMap st = new HashMap();

        GregorianCalendar x = new GregorianCalendar(1969, 21, 7);
        GregorianCalendar y = new GregorianCalendar(1969, 4, 12);
        GregorianCalendar z = new GregorianCalendar(1969, 21, 7);

        st.put(x,  "human in space");
        x.set(1969, 4, 12);

        System.out.println(st.get(x));
        System.out.println(st.get(y));
        System.out.println(st.get(z));


    }

}

Here: x.set(1969, 4, 12); you change already defined object after putting into Map .

Never change internal values of an object which is used for Map key. It brakes hashCode() value, equals() method, and after that your map can be thrown out to the dustbin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM