为什么具有相同值的不同对象会导致 HashSet.contains 到 return 为真?
Why do different objects with same values cause HashSet.contains to return true?
下面是一些代码,用于查看迷宫中是否存在从左上角到右下角的路径。我对这段代码的问题是我们检查 failedPoints.contains(p)
的地方:我们怎么能得到 true
?
在我们 if(failedPoints.contains(p))
之前,我们正在创建一个新的 Point
对象。即使新的 Point
对象与 failedPoints
中的另一个 Point
具有相同的 row
和 col
值,对象也会不同,所以不应该 failedPoints.contains(p)
总是returnfalse
?
boolean getPath(boolean[][] maze, int row, int col, ArrayList<Point> path, HashSet<Point> failedPoints){
/*if out of bounds or not available, return*/
if(col<0 || row<0 || !maze[row][col]){
return false;
}
Point p = new Point(row,col);
/* If we've already visited this cell return*/
if(failedPoints.contains(p)){
return false;
}
boolean isAtOrigin = (row == 0) && (col == 0);
/*If there's a path from start to my current location, add my location.*/
if(isAtOrigin || getPath(maze,row,col -1, path, failedPoints) || getPath(maze,row-1, col, path,failedPoints)){
path.add(p);
return true;
}
failedPoints.add(p); //Cache result
return false;
}
这取决于Point
class的定义。
看看the HashSet.contains Javadocs:
public boolean contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
所以如果 Point
class 定义了一个 equals
方法来检查它的行和列是否与另一个点的行和列相同(以及定义了一个 hashCode 不违反约定的方法),然后 failedPoints.contains()
将 return 如果另一个 Point
等于被测试的方法存在于集合中。
下面是一些代码,用于查看迷宫中是否存在从左上角到右下角的路径。我对这段代码的问题是我们检查 failedPoints.contains(p)
的地方:我们怎么能得到 true
?
在我们 if(failedPoints.contains(p))
之前,我们正在创建一个新的 Point
对象。即使新的 Point
对象与 failedPoints
中的另一个 Point
具有相同的 row
和 col
值,对象也会不同,所以不应该 failedPoints.contains(p)
总是returnfalse
?
boolean getPath(boolean[][] maze, int row, int col, ArrayList<Point> path, HashSet<Point> failedPoints){
/*if out of bounds or not available, return*/
if(col<0 || row<0 || !maze[row][col]){
return false;
}
Point p = new Point(row,col);
/* If we've already visited this cell return*/
if(failedPoints.contains(p)){
return false;
}
boolean isAtOrigin = (row == 0) && (col == 0);
/*If there's a path from start to my current location, add my location.*/
if(isAtOrigin || getPath(maze,row,col -1, path, failedPoints) || getPath(maze,row-1, col, path,failedPoints)){
path.add(p);
return true;
}
failedPoints.add(p); //Cache result
return false;
}
这取决于Point
class的定义。
看看the HashSet.contains Javadocs:
public boolean contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
所以如果 Point
class 定义了一个 equals
方法来检查它的行和列是否与另一个点的行和列相同(以及定义了一个 hashCode 不违反约定的方法),然后 failedPoints.contains()
将 return 如果另一个 Point
等于被测试的方法存在于集合中。