为什么 ts.contains(t)
返回 false
我该如何解决?
请看一下我的代码:
class MyList {
private String x;
public MyList (String x) {
this .x = x;
}
public String toString () {
return x;
}
public static void main ( String [] args ) {
List<MyList> ts = new ArrayList<MyList>();
ts.add (new MyList ("one"));
ts.add (new MyList ("two"));
ts.add (new MyList ("three"));
MyList t = new MyList("one");
System.out.println ("Is t in ts? " + ts.contains(t));
}
}
谢谢大家的帮助。 SamzSakerz 和 michaeak 的答案都能正常工作。
最佳答案
只需实现equals()
方法:
class MyList {
private String x;
public MyList (String x) {
this .x = x;
}
@Override
public String toString () {
return x;
}
public static void main ( String [] args ) {
List<MyList> ts = new ArrayList<MyList>();
ts.add (new MyList ("one"));
ts.add (new MyList ("two"));
ts.add (new MyList ("three"));
MyList t = new MyList("one");
System.out.println ("Is t in ts? " + ts.contains(t));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MyList other = (MyList) obj;
if (x == null) {
if (other.x != null) {
return false;
}
} else if (!x.equals(other.x)) {
return false;
}
return true;
}
}
输出 t 在 ts 中吗?真
equals()
方法是为 Object
类定义的,它是每个类的顶级类。 contains()
方法根据契约(Contract)检查请求的对象 a 是否包含在列表中(即相同的对象包含在列表中)或者是否相等的对象 b(即 a.equals(b) 为真)包含在列表中。
List.contains(obj)
不需要实现hashCode
方法,但是建议实现hashCode()
每当您实现 equals()
并确保在两种方法中依赖于相同的属性时。
关于java - 检查对象列表是否包含Java中的另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53738048/