Java的ArrayList中包含始终返回false虽然它包含相同的值 [英] Java ArrayList Contain always return false although it contain the same value
问题描述
这是我的洞级
class Hole {
public int a;
public int b;
Hole(int a, int b) {
this.a = a;
this.b = b;
}
所以,我将包含多种了几个洞一个ArrayList
So i adding an ArrayList that contain several several hole
public void checkPathLoop(int x, int y) {
//rough code
ArrayList<Hole> leftFlowInnerHole = new ArrayList<>();
//left holes rules
leftFlowInnerHole.add(new Hole(0, 1));
leftFlowInnerHole.add(new Hole(1, 5));
leftFlowInnerHole.add(new Hole(5, 4));
leftFlowInnerHole.add(new Hole(0, 4));
当我添加
Hole userInputHole = new Hole(0,1);
System.out.print(leftFlowInnerHole.contain(userInputHole));
它总是返回false!它想返回true。
it always return false !! it suppose to return true.
有什么我错过?
感谢您提前
推荐答案
您需要覆盖从对象herited的
类(以及因此也等于
法散code
来尊重合同,请参阅Why我需要重写在Java中的平等和散列code的方法呢?)在孔
类。
You need to override the equals
method herited from the Object
class (and hence also hashCode
to respect the contract, see Why do I need to override the equals and hashCode methods in Java? ) in your Hole
class.
如果此列表包含指定的元素,则返回true。更多
正式,如果,如果这个列表只包含至少有一个返回true
元素e( 0 == NULLË== 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)
).
基本上是默认等于
实施是一个 ==
两个对象之间的比较
Basically the default equals
implementation is an ==
comparison between the two objects
public boolean equals(Object obj) {
return (this == obj);
}
由于您创建了两个不同的对象,而它们具有相同的价值属性,他们是两个distincts对象,因此此== OBJ
收益假
。
如果你这样做:
Hole a = new Hole(0,1);
leftFlowInnerHole.add(a);
System.out.print(leftFlowInnerHole.contains(a));
您会看到,它输出真正
。
这篇关于Java的ArrayList中包含始终返回false虽然它包含相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!