I have a Array
of object, since I am using a 3rd party library, the array is got by calling one method from the library, I am not able to access the MyObject
class.
//I have no access to MyObject class, I am sure the objects contain duplicated elements.
MyObject[] objects = SOME_LIB_CLASS.getObjects();
System.out.println("length is "+ objects.length); //length is 6
I try to remove duplicated elements in objects, I use Set
:
Set<MyObject> objectSet = new HashSet<MyObject>(Arrays.asList(objects));
System.out.println("length is "+ objectSet.size()); //length is 6 still
But the objectSet
still contains duplicated elements, why & how to solve my problem without iterate through the array?
It contains duplicated entries, because
MyObject
doesn't overwriteequals
andhashcode
. If you can't access the class, then you have to iterate over the array, and check for differences manually.If the set still contains "duplicate" elements than the equals method of your objects does not what you expect it to do.
Duplicates in a
HashSet
are determined by theequals
implementation.If you can not change the implementation of
MyObject.equals()
( because you don't have the source code - it is a library class), I recommend to use aTreeSet
and provide a special comparator.For example
Can you try to print hashcode of the objects, I think those objects are not same but have same values for there fields. and if MyObject is your class, override equals and hascode method to make set working.
Hope below code help you
It will remove all duplicate values from arraylist