Java:添加到集合中的重复对象? [英] Java: Duplicate objects getting added to set?

查看:196
本文介绍了Java:添加到集合中的重复对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行下面的代码,那么输出是2,这意味着该集合包含2个元素。但是我认为这个集合应该包含1,因为基于 hashcode()值以及 .equals()方法这两个对象是相等的。
看起来像我理解中的一些明显的错误?

  package HELLO; 

import java.util.HashSet;
import java.util.Set;

public class Test {

public static void main(String [] args)throws Exception {
Set< Alpha> s = new HashSet< Alpha>();
Alpha a1 =新的Alpha();
Alpha a2 =新的Alpha();
s.add(a1);
s.add(a2);
System.out.println(s.size());
}
}

class Alpha {
int a = 10;

public int hashcode(){
return a;
}

public boolean equals(Object obj){
return(obj instanceof Alpha&&((Alpha)obj).a == this.a);
}

public String toString(){
returnAlpha:+ a;


$ / code $ / pre

解决方案

hash c ode方法不会覆盖Object类的散列 C ode方法,因此您的equals方法会破坏合约,因为它不符合hashCode结果,您可以相等但具有不同hashCodes的对象。



记住:在覆盖方法时,您应该总是使用 @Override 注释,因为这可以帮助您捕获这个和类似的错误。

  @Override // **不要忘记这个注释
public int hashCode(){// ***注意大写的C
返回a;
}

此外,您还需要改进代码格式,特别是在此处发布代码时为我们的审查。如果符合标准,我们将能够更好地理解您的代码并为您提供帮助(这就是标准存在的原因)。因此,请尽量保持缩进与同一块中缩进相同级别的所有代码行保持一致,并且您需要确保基本级代码(包括导入,外部类声明和其结束大括号)左对齐:

  import java.util.HashSet; 
import java.util.Set;

public class Test {

public static void main(String [] args)throws Exception {
Set< Alpha> s = new HashSet< Alpha>();
Alpha a1 =新的Alpha();
Alpha a2 =新的Alpha();
s.add(a1);
s.add(a2);
System.out.println(s.size());
}
}

class Alpha {
int a = 10;

@Override
public int hashCode(){
return a;
}

public String toString(){
returnAlpha:+ a;

$ b @Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass()!= obj.getClass())
return false;
Alpha其他=(Alpha)obj;
if(a!= other.a)
return false;
返回true;


$ / code $ / pre

有关这方面的详细评论,请阅读:在Java中重写equals和hashCode


If I run the below code then the output is 2 which means that the set contains 2 elements. However I think that set should contain 1 since both the objects are equal based on hashcode() value as well as .equals() method. Seems like some obvious mistake in my understanding ?

package HELLO;

import java.util.HashSet;
import java.util.Set;

public class Test {

    public static void main(String[] args) throws Exception {
        Set<Alpha> s = new HashSet<Alpha>();
        Alpha a1 = new Alpha();
        Alpha a2 = new Alpha();
        s.add(a1);
        s.add(a2);
        System.out.println(s.size());
    }
}   

class Alpha {
    int a = 10;

    public int hashcode() {
        return a;
    }

    public boolean equals(Object obj) {
        return (obj instanceof Alpha && ((Alpha) obj).a == this.a);
    }

    public String toString() {
        return "Alpha : " + a;
    }
}

解决方案

Your hashcode method does not override the Object class's hashCode method and thus your equals method breaks contract since it doesn't agree with the hashCode results, and you can have objects that are "equal" but have different hashCodes.

Remember: You should always use the @Override annotation when overriding methods as this will help you catch this and similar errors.

@Override  // ** don't forget this annotation
public int hashCode() { // *** note capitalization of the "C"
  return a;
}

Also, you will want to improve your code formatting, especially when posting code here for our review. We will be able to better understand your code and help you if it conforms to standards (that's why standards exist). So try to keep your indentations consistent with all code lines that are in the same block indented at the same level, and you will want to be sure that base level code, including imports, outer class declarations and its end curly brace, is flush left:

import java.util.HashSet;
import java.util.Set;

public class Test {

   public static void main(String[] args) throws Exception {
      Set<Alpha> s = new HashSet<Alpha>();
      Alpha a1 = new Alpha();
      Alpha a2 = new Alpha();
      s.add(a1);
      s.add(a2);
      System.out.println(s.size());
   }
}

class Alpha {
   int a = 10;

   @Override
   public int hashCode() {
      return a;
   }

   public String toString() {
      return "Alpha : " + a;
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      Alpha other = (Alpha) obj;
      if (a != other.a)
         return false;
      return true;
   }
}

For a beautiful review on this, please read: Overriding equals and hashCode in Java

这篇关于Java:添加到集合中的重复对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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