如何做一个ArrayList中的contains()方法评估对象? [英] How does a ArrayList's contains() method evaluate objects?
问题描述
说我创建一个对象,并将其添加到我的的ArrayList
。如果我再有完全相同的构造函数的输入创建另一个对象,将包含()
方法评估两个对象是一样的吗?假设构造并不做任何事情好笑的输入,并存储在两个对象变量是相同的。
Say I create one object and add it to my ArrayList
. If I then create another object with exactly the same constructor input, will the contains()
method evaluate the two objects to be the same? Assume the constructor doesn't do anything funny with the input, and the variables stored in both objects are identical.
ArrayList<Thing> basket = new ArrayList<Thing>();
Thing thing = new Thing(100);
basket.add(thing);
Thing another = new Thing(100);
basket.contains(another); // true or false?
class Thing {
public int value;
public Thing (int x) {
value = x;
}
equals (Thing x) {
if (x.value == value) return true;
return false;
}
}
这是怎么了类
应实行有包含()
收益真
?
推荐答案
的ArrayList 工具
List接口。
ArrayList implements
the List Interface.
如果你在看<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains%28java.lang.Object%29\">Javadoc为列表
在包含
方法,你会看到它使用了等于()
方法来评价,如果两个对象是相同的。
If you look at the Javadoc for List
at the contains
method you will see that it uses the equals()
method to evaluate if two objects are the same.
这篇关于如何做一个ArrayList中的contains()方法评估对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!