java - ArrayList 的 contains() 方法总是返回带有自定义对象的 false

标签 java arraylist contains

我在继续我的代码时遇到了一些麻烦,我会给你一个简单的例子(虽然它会更复杂一些,但这个简单的代码也不能正常工作)。

class Sign {

  private String char;
  private Integer freq;

  public Sign(String c) {
  this.char = c; 
  }

  @Override
  public boolean equals(Object o) {

   String check = (String)o;
   return check.equals(this.char);
  }

  @Override
  public int hashCode() {

    int hash = 7;
    hash = 31 * hash + this.char.hashCode();
    return hash;
}

}

为了简单起见,我假设在 equals 方法中总是会有一个字符串。还有一些 hashCode() 也可以确保 contains() 方法可以工作,这里是测试本身:

    ArrayList<Sign> queueOfSigns = new ArrayList<>();

    Sign test = new Sign("C");
    String c = "C";
    queueOfSigns.add(test);

    if(queueOfSigns.contains("C"))
        System.out.println("I am here!");

无论如何,这个简单的测试代码在那种情况下总是返回 false - 所以“我在这里”消息永远不会出现。我一直在尝试一些不同的方法来处理我的代码,但这是因为这样做的想法是从字符串文本中获取单个字符并检查单个字符是否已经存在于 ArrayList 中。尽管如此 - 如果这个简单的测试无法正常工作,我无法继续,所以我想问你 - 我错过了什么。这是我第一次真正使用 equals() 和 hashCode() 方法让我自己的对象与 contains() 方法一起正常工作。

最佳答案

你的 equals实现不正确。 equals 有一个特定的契约;该代码试图违反该契约(Contract)。来自文档:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

无法将您的 Signequals 的实例生成为字符串。

关于java - ArrayList 的 contains() 方法总是返回带有自定义对象的 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52317618/

相关文章:

c# - 在 C# NET 中运行 Java 应用程序

kotlin - 类型不匹配Kotlin和getStringArrayListExtra

c# - 如何使用 LINQ Contains(string[]) 而不是 Contains(string)

arrays - 在 Swift 中使用值数组按属性过滤对象数组

java - 为什么 JUnit 只在第一次失败之前运行 Theory 的测试用例?

java - 从 MDX 请求 Mondrian 检索数据

Java:取消标记文件是只读的

java - Android onTap Intent 数组

java - 洗牌的随机性

xml - 在 XML 树中搜索特定文本并在下一个节点中提取文本