Java ArrayList Contain 尽管包含相同的值,但它始终返回 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.
有什么我想念的吗??
提前致谢
推荐答案
您需要重写从 Object
类继承的 equals
方法(因此也是 hashCode
遵守合约,见 为什么我需要在您的 Hole
类中覆盖 Java 中的 equals 和 hashCode 方法?).
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 使得 (o==null ? e==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)
).
基本上默认的 equals
实现是两个对象之间的 ==
比较
Basically the default equals
implementation is an ==
comparison between the two objects
public boolean equals(Object obj) {
return (this == obj);
}
由于您创建了两个不同的对象,虽然它们具有与属性相同的值,但它们是两个不同的对象,因此 this == obj
返回 false
.
Since you created two different objects, while they have the same value as attributes they're two distincts objects and hence this == obj
returns false
.
如果你这样做了:
Hole a = new Hole(0,1);
leftFlowInnerHole.add(a);
System.out.print(leftFlowInnerHole.contains(a));
你会看到它输出 true
.
这篇关于Java ArrayList Contain 尽管包含相同的值,但它始终返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!