【问题标题】:Why containValue method of HashMap class is returning False for the below program?为什么 HashMap 类的 containsValue 方法为以下程序返回 False?
【发布时间】:2016-03-16 19:12:33
【问题描述】:

在这里,我试图同时覆盖 equals 方法和哈希码方法。但是 containsValue() 方法抛出 False。甚至哈希码覆盖的类也被调用,但我认为 equals 方法没有被正确调用。请帮我解决这个问题。

import java.util.*; 

class Test{

    int i;

    Test(int i)
    {
        this.i=i;
    }

    public boolean equals(Test t)
    {
        if(this.i==t.i){
            return true;
        }
        else{
            return false;
        }
    }

    public int hashCode() { //Overriding hashCode class
        int result = 17; 
        result = 37*result + Integer.toString(i).hashCode(); 
        result = 37*result; 
        return result; 
    }
}

class TestCollection13{  
    public static void main(String args[]){  
        HashMap<Integer,Test> hm=new HashMap<Integer,Test>();  
        hm.put(1,new Test(1));  
        hm.put(2,new Test(2));  
        hm.put(3,new Test(1));  
        hm.put(4,new Test(4));  

        for(Map.Entry m:hm.entrySet()){
            Test t2=(Test)m.getValue();
            System.out.println(m.getKey()+" "+t2.hashCode());
        }

        System.out.println(hm.containsValue(new Test(2)));
    }
}

【问题讨论】:

  • 谢谢你,但我面临的问题是即使没有覆盖 hashCode 方法,它也会返回 true。

标签: java hashmap


【解决方案1】:

您的方法public boolean equals(Test t) 不会覆盖Object.equals(Object)。您需要更新方法签名并检查类类型:

@Override
public boolean equals(Object o) {
    return o instanceof Test
            && ((Test)o).i == this.i;
}

【讨论】:

    【解决方案2】:

    equals 应定义为采用 Object,而不是 Test

    @Override
    public boolean equals(Object other)
    

    您可以通过使用@Override 显式注释方法来轻松检测到此错误,在这种情况下编译器会检测到此错误。

    【讨论】:

      【解决方案3】:

      方法equals()Object 作为参数,因此在您的代码中,您不是覆盖equals() 方法而是重载它。所以需要将传入的参数改为Object。你的方法应该是这样的:

          @Override
      public boolean equals(Object o) {
          if (this == o) return true;
          if (!(o instanceof Test)) return false;
          Test test = (Test) o;
          return this.i == test.i;
      }
      

      我还会为你的 i 成员添加 getter 和 setter。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-09
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 2016-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多