How to remove duplicate objects in an ArrayList?

2

Hello I have an array of objects. but these objects end up repeating themselves, so I wanted a naneira to remove the duplicates.

I've tried using hasSet, but it does not seem to work with objects.

Set nova = new HashSet<>();
nova.addAll(Objetos);
Objetos.clear();
Objetos.addAll(nova);

I've tried to use a comparison if but it did not work out either.

List<T> naoDuplicado = new ArrayList<T>();
for (T obj : naoDuplicado) {
    if (!naoDuplicado.contains(Obj)) {
        naoDuplicado.add(element);
    }
}
    
asked by anonymous 18.05.2016 / 18:02

1 answer

1

You can and should use HashSet , but the object that you are adding to the collection must implement the equals (and hashCode ). For it is through equals HashSet defines duplicity.

Implement in this context means you reimplement / overwrite the method according to your equality rule.

The answer from question should help with your implementation.     

18.05.2016 / 18:18