Reputation: 59
This is some basic problem as I think.
I have the object coordinate:
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;
}
}
And I want to add some of this type of element to a vector, but if I have one of this in an other one then skip it. I tried like this:
ArrayList nat = new ArrayList (); //not available
ArrayList at = new ArrayList (); //available
Here I upload the nat
vector with some elems.
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);
}
}
But at the end if I print both of vectors than the result is:
at: [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]
How can I add only that coordinates which are not in the other?
Upvotes: 0
Views: 74
Reputation: 1552
Implement hashcode()/equal()
methods & use HashSet collection. HashSet
is the collection that allows unique values and it is ideal collection in your case. When you attempt to add an element to HashSet and if it is already present, then it won't add and will return false
. Please implement around HashSet instead of Vector.
Upvotes: 1
Reputation: 1010
Implement hashCode() and equals() in your Coordinate class and prefer ArrayList to Vector
Upvotes: 1