I have to add only unique elements to an ArrayList. How can I override the equals method for that purpose? I want something like:
public boolean equals (Object in) {
if(in == null) {
return false;
}
else if(in instanceof UniqueFruits) {
// ?? check whether the newly added element exists or not
return true;
}
else {
return false;
}
}
How to check whether the newly added element exists or not? I have to check on the Fruit Names.
It sounds like you want to use a
Setimplementation. If order doesn’t matter, just useHashSet. If you want to keep insertion-order, useLinkedHashSet. Or, to maintain natural ordering, useTreeSet.In any case, make sure to override your element object’s
equalsmethod. What you have is a good start. After checkingin instanceof UniqueFruits, castintoUniqueFruits:You can then check each relevant field using
equalsin turn (make sure to check fornullfirst if a field is nullable). Any modern IDE will help you generateequalsautomatically. It may be educational to try it yourself first, then compare with the generated version.Make sure to override
hashCodealso (IDEs will similarly help you with this, and there is plenty of reading online about the matter – just search).If you use
TreeSet(or some otherSortedSetimplementation), your element object should either implementComparableor else you should provide theSortedSetwith aComparator.