java - 如何在一组自定义对象中查找对象

标签 java hashset

下面的代码包含一组自定义对象。我正在尝试搜索其中的一个对象。

我已经重写了 equals() 方法以将其与特定字段进行匹配,但我无法理解为什么它找不到它。

"XX\tNot Found\tXX"

正在打印 的

"Found!!"

导入java.util.HashSet; 导入java.util.Set;

public class TestEquals {

  private static Set<CustomObject> setCustomObjects;    

  public static void main(String[] args){
    setCustomObjects = new HashSet<CustomObject>();

    setCustomObjects.add(new CustomObject(2, "asas"));
    setCustomObjects.add(new CustomObject(3, "gdhdf"));
    setCustomObjects.add(new CustomObject(4, "bnbv"));
    setCustomObjects.add(new CustomObject(5, "ljhj"));

    AnotherObject anObj = new AnotherObject(3, 4);

    if(setCustomObjects.contains(anObj)){
        System.out.println("Found!!");
    }else{
        System.out.println("XX\tNot Found\tXX");
    }
  }
}


class CustomObject {

  public CustomObject(int test, String name) {
    this.test = test;
    this.name = name;
  }

  private int test;
  private String name;

  @Override
  public boolean equals(Object obj) {
    if(obj instanceof AnotherObject){
        AnotherObject temp = (AnotherObject)obj;
        System.out.println("test" + temp.getOtherTest());
        return this.test == temp.getOtherTest();
    }
    return true;
  }

  @Override
  public int hashCode() {
    int hash = 22;
    hash = 32 * hash + this.test;
    return hash;
  }

}


class AnotherObject {

  public AnotherObject(int otherTest, double test2) {
    this.otherTest = otherTest;
    this.test2 = test2;
  }

  private int otherTest;
  private double test2;

  public int getOtherTest() {
    return otherTest;
  }
  public void setOtherTest(int otherTest) {
    this.otherTest = otherTest;
  }
}

最佳答案

您尚未覆盖 AnotherObject 中的 equalshashCode。这样做,您应该会得到您所期望的结果。

关于java - 如何在一组自定义对象中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16165258/

相关文章:

java - 使用 Java 连接 MySQL 时出现“通信链路故障最后一个数据包发送...”

java - 只插入一次

java - 类构造函数不区分 args... 和 args[][]

c# - 如何创建具有不同元素的 HashSet<List<Int>>?

java - Dalvik 的内存模型和 Java 的一样吗?

java - 删除二维ArrayList中的重复条目

java - 在 Java 中为 HashSet 构建字符串 - 无法正确循环大字符串

java - 使用TreeSet对JList进行排序

java - 从两个哈希集中删除重复项

java - 用 Java 实现的 str_pad