用最好的方式包含在Java中的ArrayList? [英] Best way to use contains in an ArrayList in Java?
问题描述
我在Java的一个ArrayList是由包含两个字符串和一个整数的类型。我可以成功地测试此ArrayList的一个元素等于另一个,但我发现,含有方法失败。相信这是由于这样的事实,即我的类型不是原始
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:
-
要实现自己的包含通过ArrayList中迭代和测试对一个我正在寻找每一个元素的平等,再破环的方法。
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.
推荐答案
最有可能的,你干脆忘了覆盖等于()
和散code()
在你的类型。 等于()
是包含()
支票。
Most likely, you have simply forgotten to override equals()
and hashCode()
in your type. equals()
is what contains()
checks for.
从<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#contains%28java.lang.Object%29\">Javadoc:
返回真正
如果此列表包含指定的元素。更正式地说,返回真正
当且仅当此列表包含至少一个元素电子
,使得(O == NULLË== NULL:o.equals(e)项)
。
Returns
true
if this list contains the specified element. More formally, returnstrue
if and only if this list contains at least one elemente
such that(o==null ? e==null : o.equals(e))
.
由于默认实现<一个href=\"http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29\"><$c$c>equals$c$c>参考相等测试,它不适合自定义数据类型,如这一个。
Since the default implementation of equals
tests for reference equality, it's not suitable for custom data types like this one.
(如果你没有重载等于
和散code
,使用类型,键在的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!
...
}
}
这是使用一个非常有力的论据 @覆盖
注释;第一个例子是在编译时,如果标注了 @覆盖
都失败了。
这篇关于用最好的方式包含在Java中的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!