Compare two list

3

I have a list

List<Comentarios> comentarios
List<Comentarios> comentariosSP

The first list I get the data from a webserver, the second one from a SharedPreferences.

I tried to compare them

comentarios.equals(comentariosSP)

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

reminding me that I need to verify that the attribute data is the same. EX:

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

Can you do this without going through the entire list?

    
asked by anonymous 05.11.2016 / 15:44

2 answers

5

You can use the equals() method of the List if you override the method of the Comments class to indicate when two Comet objects 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 the same if they have the same number of items, in the same order.

    
05.11.2016 / 16:25
0

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

Using the equals () of the List you compare the values themselves.

    
07.11.2016 / 15:00