Reputation: 369
Could somebody tell me what the following line in the code that was provided by my tutor is supposed to be doing?
if (data.contains(entry))
Full method:
public String add(Entry entry) {
if (entry == null)
return "Error: null entry";
if (data.contains(entry))
return "Error: this entry already in the book";
boolean done = data.add(entry);
if (done)
return " entry added";
else
return "entry could not be added";
}
I thought it was checking for an existing entry with the same details within the ArrayList but when I add a duplicate entry it doesnt go into the if
statement so figured I assumed wrong? I searched around on the Internet and it says it's for this purpose so why doesn't it work for me?
Upvotes: 1
Views: 2542
Reputation: 69399
Remember that contains()
performs an equality check with equals()
. So unless your object overrides that method, it will not consider objects to be equal unless they are the same object reference.
Of course, don't override equals()
without overriding hashCode()
too.
Finally, if you don't want duplicate objects consider using a Set
.
Upvotes: 7
Reputation: 122026
List's contains()
method you will see that it uses the equals
() method to evaluate if two objects are the same.
internal logic as per docs
(o==null ? e==null : o.equals(e));
So you have to ovveride
the equals
method to compare
them
Upvotes: 0