This is a pretty common question, but I could not find this part:
Say I have this array list:
List<MyDataClass> arrayList = new List<MyDataClass>;
MyDataClass{
String name;
String age;
}
Now, I need to find duplicates on the basis of age in MyDataClass and remove them. How is it possible using something like HashSet as described here?
I guess, we will need to overwrite equals in MyDataClass?
- But, what if I do not have the luxury of doing that?
- And How does HashSet actually internally find and does not add duplicates? I saw it’s implementation here in OpenJDK but couldn’t understand.
I’d suggest that you override both
equalsandhashCode(HashSetrelies on both!)To remove the duplicates you could simply create a new
HashSetwith the ArrayList as argument, and then clear the ArrayList and put back the elements stored in theHashSet.And then do
Then I’d suggest you do some sort of decorator-class that does provide these methods.