I have requirement to remove the duplicate object from my arraylist of object. I tried it by making to arraylist of objects. First one contains all objects including duplicate and the another contain only the unique one.
ArrayList<ListTableClass> ltc = new ArrayList<ListTableClass>();//has duplicate
ArrayList<ListTableClass> ltc2 = new ArrayList<ListTableClass>();//unique
And i used contains method to check for dublicates like this:
for (ListTableClass element : ltc) {
if (!ltc2.contains(element)) {
ltc2.add(element);
}
}
but this does not remove duplicates. It adds all the elements of ltc to ltc2. Don't know why? ltc does contain duplicate objects.
Because the function "contains" of ArrayList compare with two objects in their functions hashcode & equals, so you must override the function "hashCode" & "equals" of Class ListTableClass.
example:
output before override hashCode:
add override function hashCode:
then output is:
there is not obj3 because of obj3's hashcode & its property is equal with obj0