gpt4 book ai didi

java - 检查a是否包含Java中的对象

转载 作者:行者123 更新时间:2023-12-03 23:13:54 24 4
gpt4 key购买 nike

我有以下对象,

public class Pair {
private int row;
private int col;

public Pair(int row, int col){
this.row = row;
this.col = col;
}

public int getRow(){
return row;
}
public int getCol(){
return col;
}
}

我将这些对存储在一个队列中,但不想检查队列中是否已经包含该对。这是我的代码。

Queue<Pair> queue = new LinkedList<>();
if(!queue.contains(new Pair(curr.getRow(), curr.getCol()){
//do something
}

这不起作用,队列正在存储重复值。有人可以帮助 mw 了解原因以及解决方法吗?

最佳答案

您没有覆盖 Object.equals(Object)所以你只为引用身份获得平等。你需要添加类似的东西

@Override
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair other = (Pair) o;
return row == other.row && col == other.col;
}
return false;
}

并且无论何时覆盖equals,强烈建议您覆盖Object.hashCode()以及(例如与 HashSet 一起工作)

@Override
public int hashCode() {
return Integer.hashCode(row) + Integer.hashCode(col);
}

最后,您不妨覆盖 Object.toString()所以你可以很容易地显示这些Pair。类似的东西,

@Override
public String toString() {
return String.format("Pair: (%d, %d)", row, col);
}

关于java - 检查a是否包含Java中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36318186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com