本文翻译自:How does a ArrayList's contains() method evaluate objects?
Say I create one object and add it to my ArrayList
. 说我创建一个对象并将其添加到我的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? 如果然后使用完全相同的构造函数输入创建另一个对象, contains()
方法是否会将两个对象评估为相同? 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;
}
}
Is this how the class
should be implemented to have contains()
return true
? 这是应该如何实现class
以使contains()
返回true
吗?
#1楼
参考:https://stackoom.com/question/B5SP/ArrayList的contains-方法如何评估对象
#2楼
class Thing {
public int value;
public Thing (int x) {
value = x;
}
equals (Thing x) {
if (x.value == value) return true;
return false;
}
}
You must write: 您必须写:
class Thing {
public int value;
public Thing (int x) {
value = x;
}
public boolean equals (Object o) {
Thing x = (Thing) o;
if (x.value == value) return true;
return false;
}
}
Now it works ;) 现在可以了;)
#3楼
I think that right implementations should be 我认为正确的实现应该是
public class Thing
{
public int value;
public Thing (int x)
{
this.value = x;
}
@Override
public boolean equals(Object object)
{
boolean sameSame = false;
if (object != null && object instanceof Thing)
{
sameSame = this.value == ((Thing) object).value;
}
return sameSame;
}
}
#4楼
Just wanted to note that the following implementation is wrong when value
is not a primitive type: 只是要注意,当value
不是原始类型时,以下实现是错误的:
public class Thing
{
public Object value;
public Thing (Object x)
{
this.value = x;
}
@Override
public boolean equals(Object object)
{
boolean sameSame = false;
if (object != null && object instanceof Thing)
{
sameSame = this.value == ((Thing) object).value;
}
return sameSame;
}
}
In that case I propose the following: 在这种情况下,我提出以下建议:
public class Thing {
public Object value;
public Thing (Object x) {
value = x;
}
@Override
public boolean equals(Object object) {
if (object != null && object instanceof Thing) {
Thing thing = (Thing) object;
if (value == null) {
return (thing.value == null);
}
else {
return value.equals(thing.value);
}
}
return false;
}
}
#5楼
ArrayList使用在类(您的案例Thing类)中实现的equals方法进行相等比较。
#6楼
It uses the equals method on the objects. 它在对象上使用equals方法。 So unless Thing overrides equals and uses the variables stored in the objects for comparison, it will not return true on the contains()
method. 因此,除非Thing重写equals并使用存储在对象中的变量进行比较,否则它不会在contains()
方法上返回true。