Reputation: 31
I had overridden equals for an object class so that every time a duplicate occurred when adding objects of that class to an array list, a dialogue box would pop up. But this pops up with the remove() for array list. Is there a way I can make this conditional based on which method uses equals? Like two different equals, or maybe use another array list method that can let you specify which equals to use?
Edit: Sorry about being very unclear with my question. Here's my overridden equals and hashcode methods:
@Override
public boolean equals(Object s) {
if(!(s instanceof Car)) {
return false;
}
Car s2 = (Car)s;
if(this.name.equals(s2.name) && this.ride.equals(s2.ride)){
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Delete Item");
alert.setHeaderText(
"Are you sure?");
alert.showAndWait();
return true;
}
return false;
}
@Override
public int hashCode(){
int hashC;
hashC = name.hashCode();
hashC *= ride.hashCode();
return hashC;
}
As for the rest, I use the HashSet to remove duplicates automatically.
Upvotes: 0
Views: 112
Reputation: 33466
Don't make equals
do anything more than what the contract says it should do. Instead, use a check for indexOf
to see if the element already exists in the List
.
if (list.indexOf(object) != -1) {
dialog.show();
} else {
list.add(object);
}
If you don't want the collection to contain any duplicates and you don't care about the order of elements, however, you should be using a HashSet
instead of a List
. This will automatically keep out duplicates by checking equals
, and will return false on the add
method when a duplicate exists. You will need to override the hashCode
method on your object also.
if (!set.add(object)) {
dialog.show();
}
Upvotes: 1