简体   繁体   English

为什么我的哈希映射代码打印为空?

[英]Why does my hash map code print null?

I have the following code and I want to print x , y , and z . 我有以下代码,我想打印xyz When I do that, I expect (1969, 21, 7) , (1969, 4, 12) , and (1969, 21, 7) respectively. 当我这样做时,我分别期待(1969, 21, 7)(1969, 4, 12)(1969, 21, 7) Instead, I get null null null . 相反,我得到null null null

My question is, why does the code below print null for x, y, and z instead of the actual date? 我的问题是,为什么下面的代码为x,y和z而不是实际日期打印为空?

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); 这里: x.set(1969, 4, 12); you change already defined object after putting into Map . 放入Map 更改已定义的对象。

Never change internal values of an object which is used for Map key. 切勿更改用于Map键的对象的内部值。 It brakes hashCode() value, equals() method, and after that your map can be thrown out to the dustbin. 它会驱动hashCode()值, equals()方法,之后你的地图就会被扔到垃圾箱里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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