DEV Community

Discussion on: Getting duplicated objetcs in ArrayList

Collapse
 
leoat12 profile image
Leonardo Teteo • Edited

Do you want to count the number of repeated objects in an ArrayList, right?
With that I assume that you are talking about complex objects, a class that has many fields, not something like a String, Integer, and so on.

There is a trick that I believe is worth mentioning, it was the first thing that came to my mind when I read your problem. There is a class called Set. It is not the same as a List, but it is also a collection of objects, with the difference that it cannot have repeated objects in it.
If you transform a List into a Set and compare the size of both, you will have the number of repeated objects. Just beware that to work properly the class of the object must have the methods equals() and hashCode() properly implemented. If you don't know what they are just yet, just let me know, but give it a try, it will be a interesting experience. ;-)