Why are you returning a List in the first place? To the Java Tutorials, where you find there are lots of different kinds of Collection, some which permit duplicates and some which don't. Using a different kind of Collection might sort out your problem.
But this depends on the equals() and hashCode() methods being correctly overridden in your class.
Joined: Nov 27, 2008
Hi Campbell i tried this ..
With the hope that the Set will not permit dupicates, but i still get the same results
Joined: Oct 13, 2005
That looks correct to me. Have a look at the API for LinkedHashSet and find the add method, and that gives the details. Do you really need to return a List; can you return a Set?
Change the body of the for-each loop to read this, temporarily, as a testing strategy:
System.out.printf("%b ", replica.add(dto));//test
That ought to print true whenever you add, and false whenever you encounter a duplicate. If it won't print false anywhere, check the equals() and hashCode() methods of the DTO class to verify that they have been overridden correctly. They must fulfil the specification of the Object class.
I'm sure that the original poster hasnot overridden the equals() & hashcode() methods in her collection class.
So when you didn't override the equals() method, it takes the Object's equals() method which compares instances using memory references
so now consider a collection
Eventhough both the references a.k.a car & car1 has a common state like same carno like TN012345 but since equals() hasnot been overrided in Car class, the equals() from Object class which compares object reference is called.
00001234 != 00001235 car1 != car2 Eventhough both the objects have the same state
So both these objects will be added to set , which by default does not permit duplicates.