User
User

Reputation: 1726

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


    }

}

Upvotes: 1

Views: 648

Answers (1)

Andremoniy
Andremoniy

Reputation: 34900

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.

Upvotes: 3

Related Questions