在 Java 的 ArrayList 中使用 contains 的最佳方法? [英] Best way to use contains in an ArrayList in Java?

查看:27
本文介绍了在 Java 的 ArrayList 中使用 contains 的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 中有一个 ArrayList,它由包含两个字符串和一个整数的类型组成.我可以成功测试此 ArrayList 的一个元素是否等于另一个元素,但我发现 contains 方法失败.我相信这是因为我的类型不是原始类型.

I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive.

现在我看到了两个替代方案,我想知道哪个是最好的选择:

Now I see two alternatives to this and I wonder which is the best option:

  1. 通过遍历 ArrayList 并测试每个元素与我正在寻找的元素的相等性,然后打破循环来实现我自己的 contains 方法.

  1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop.

或者使用我的类型的 HashMap 作为键,以整数作为值而不是 ArrayList.在这里,我可以使用方法 containsKey 检查 HashMap 中是否已存在元素.

Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap.

对#2 方法的唯一警告是,在我的情况下,该值在很大程度上是多余的.

The only caveat with approach to #2 is that the value is largely redundant in my case.

推荐答案

很可能,您只是忘记在您的类型中覆盖 equals()hashCode().equals()contains() 检查的内容.

Most likely, you have simply forgotten to override equals() and hashCode() in your type. equals() is what contains() checks for.

来自 Javadoc:

如果此列表包含指定的元素,则返回 true.更正式地说,当且仅当此列表包含至少一个元素 e 使得 (o==null ? e==null : o.equals(e)).

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

由于equals 测试引用相等,它不适合像这样的自定义数据类型.

Since the default implementation of equals tests for reference equality, it's not suitable for custom data types like this one.

(如果您没有覆盖 equalshashCode,使用您的类型作为 HashMap 中的键同样是徒劳的.)

(And if you didn't override equals and hashCode, using your types as keys in a HashMap would be equally futile.)

请注意,要覆盖,您必须提供准确签名.

Note that to override, you must provide the exact signature.

class MyDataType {
    public boolean equals(MyDataType other) { // WRONG!
        ...
    }
    public boolean equals(Object other) { // Right!
        ...
    }
}

这是使用<的一个非常有力的论据code>@Override 注解;如果使用 @Override 注释,第一个示例将在编译时失败.

This is a very strong argument for using the @Override annotation; the first example would have failed at compile time if annotated with @Override.

这篇关于在 Java 的 ArrayList 中使用 contains 的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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