gpt4 book ai didi

java - 如何从 vector 中正确添加和删除对象

转载 作者:行者123 更新时间:2023-12-02 02:06:36 25 4
gpt4 key购买 nike

我认为这是一些基本问题。

我有对象坐标:

public class coordinate {
public int x;
public int y;

public coordinate(){
}

public coordinate(int x, int y){
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format(x + " " + y);
}
@Override
public int hashCode() {
int hash = 5;
hash = 37 * hash + this.x;
hash = 37 * hash + this.y;
return hash;
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final coordinate other = (coordinate) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
}

我想将一些这种类型的元素添加到 vector 中,但如果我在另一个 vector 中有一个这样的元素,则跳过它。我尝试过这样的:

ArrayList  nat = new ArrayList ();  //not available 
ArrayList at = new ArrayList (); //available

这里我上传了带有一些elems的nat vector 。

for (int i = 0; i < GridButtonPanel.N * GridButtonPanel.N; i++) {
int row = i / GridButtonPanel.N;
int col = i % GridButtonPanel.N;
coordinate coord = new coordinate(row, col);
if(!nat.contains(coord)){
at.add(coord);
}
}

但是最后如果我打印两个 vector ,结果是:

在:[0 0, 0 1, 0 2, 0 3, 0 4, 0 5, 0 6, 0 7, 1 0, 1 1, 1 2, 1 3, 1 4, 1 5, 1 6 , 1 7, 2 0, 2 1, 2 2, 2 3, 2 4, 2 5, 2 6, 2 7, 3 0, 3 1, 3 2, 3 3, 3 4, 3 5, 3 6, 3 7, 4 0, 4 1, 4 2, 4 3, 4 4, 4 5, 4 6, 4 7, 5 0, 5 1, 5 2, 5 3, 5 4, 5 5, 5 6, 5 7, 6 0, 6 1, 6 2, 6 3, 6 4, 6 5, 6 6, 6 7, 7 0, 7 1, 7 2, 7 3, 7 4, 7 5, 7 6, 7 7]

nat: [0 0, 0 0, 0 1, 0 2, 0 3, 0 4, 0 5, 0 6, 0 7, 0 0, 1 0, 2 0, 3 0, 4 0, 5 0 , 6 0, 7 0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 6, 7 7, 8 8, 0 0]

如何仅添加其他坐标中没有的坐标?

最佳答案

在坐标类中实现 hashCode() 和 equals(),并且更喜欢 ArrayList 而不是 Vector

关于java - 如何从 vector 中正确添加和删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50676903/

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