对象作为没有Hashcode和equals的Map键 [英] Objects as Map keys without Hashcode and equals

查看:94
本文介绍了对象作为没有Hashcode和equals的Map键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Contact
{
    int i;
    String name;
    public Contact(int iVal, String nameVal)
    {
        i = iVal;
        name = nameVal;
    }
}   

public class MultiMap
{
    public static void main (String args[])
    {
        java.util.HashMap m = new java.util.HashMap();
                Contact m1 = new Contact(1, "name");
        Contact m2 = new Contact(1, "name");
        m.put(m1, "first");
        m.put(m2, "second");
        System.out.println(m.get(m1));
        System.out.println(m.get(m2));
    }
}   

输出为:

first 
second 

这种获取方法如何表现?由于m1和M2具有相同的值并且我没有覆盖hashcode(),所以会调用Object类的equals()方法吗?

How does this "get" method behave ? As both m1 and M2 have same values and I have not overridden hashcode(), will Object class's equals() method be called ?

这是对的吗?


  1. 没有哈希码方法,因此JVM无法查看对象m1和m2是否包含不同的值

  2. 没有重写equals方法,因此调用了Object类的equals(),并且由于两个对象都不同,上面的代码工作正常,而m2不替换m1的值。


推荐答案

hashCode()和 equals(Object o)方法不会被你的类覆盖,Java只是使用对内存中对象的实际引用来计算值(即检查它是否是同一个类的实例化)。这就是为什么你仍然得到两个结果。

When the hashCode() and equals(Object o) methods are not overridden by your class, Java just uses the actual reference to the object in memory to calculate the values (ie. check if it is the same instantiation of the class). That is why you still get both results.

这篇关于对象作为没有Hashcode和equals的Map键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆