DEV Community

Dennis Quesada Cruz
Dennis Quesada Cruz

Posted on

Getting duplicated objetcs in ArrayList

Greetings community, it turns out that I have a job for the university, it's something very simple but I find it complex to achieve since I do not have much experience with Java.

I have a list of objects in an ArrayList, I can add, delete and do other operations with that list using a "for each" loop. But I do not know how to count the objects on the list that are repeated. I have looked at some articles but they are with lists of integers as an example, where one can create another Array and iterate over both and compare the values of the positions.

How would you proceed with an ArrayList of objects?

Discussion (1)

Collapse
leoat12 profile image
Leonardo Teteo • Edited on

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. ;-)