Compare Two List

Asked

Viewed 1,234 times

3

I have a list

List<Comentarios> comentarios
List<Comentarios> comentariosSP

The first list I receive data from a webserver, the second from a Sharedpreferences.

I tried to compare them

comentarios.equals(comentariosSP)

but it always returns false, even though I know the lists are identical.

remembering that I need to check if the attributes data are the same. EX:

comentarios.get(0).getComentario().equals(comentariosSP.get(0).getComentario())

You can do it without going through the whole list?

2 answers

5


You can use the method equals() of the List if over-write the method equals() class Comments to indicate when two objects Comets are the same:

@Override
public boolean equals(Object o) {
    // verifica se é o mesmo objecto
    if (this == o)
        return true;
    // verifica se é null
    if (o == null)
        return false;
    // verifica tipo e cast
    if (getClass() != o.getClass())
        return false;

    Comentarios comentarios = (Comentarios) o;
    // Comparação atributo a atributo
    // Note que cada um dos atributos têm também de implementar correctamente o método equals()
    return Objects.equals(atributo1, comentarios.atributo1)
            && Objects.equals(atributo2, comentarios.atributo2) && .....;
}

Note: Two lists are equal if they have the same number of items, equal and in the same order.

  • Thank you very much! served as a glove for me!

0

When you compare with the comments.equals(commentsSP) method, you are comparing the memory address in which the list is allocated.

using the List equals() you compare the values themselves.

Browser other questions tagged

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