How to remove Duplicate Objects in an Arraylist?

Asked

Viewed 3,763 times

2

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

I’ve tried using Hasset, but it doesn’t seem to work with objects.

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

I’ve tried to use an if comparison but it didn’t work either.

List<T> naoDuplicado = new ArrayList<T>();
for (T obj : naoDuplicado) {
    if (!naoDuplicado.contains(Obj)) {
        naoDuplicado.add(element);
    }
}

1 answer

1


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

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

The response of question should help in its implementation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.