[Solved] COMPARABLE – How to see if elements from objects are equals?


If you want to know just if an object is equal to another you have to implemet the equals method (which doesn’t requiere you to declare any interface, every class can do it)

@Override
public boolean equals(Object o) {
    CompararListas other = (CompararListas) o;
    return ...  
}

with this method you can return what makes the two objects equals to you, if you just have to look for referencia.equals(other.referencia) or if you have to compare every property like referencia.equals(other.referencia) && monto == other.monto && ...

But if you want to compare elements in order to do something like ordering them there you have to implement the Comparable interface and implement the compareTo method

@Override
public int compareTo(CompararListas o) {
    if (NumeroParte < o.NumeroParte)
        return -1;
    else if (NumeroParte > o.NumeroParte)
        return 1;
    return 0;
}

This will make the objects able to compare each other and for example know if one is “smaller” than other according to your criteria (in this example I only used NumeroParte and made it explicit to be easy to understand, but the key is that you can use any criteria you want to compare the objects and if you want order them later).

These are solutions to different problems, you have to identify which one is the better in your case.

1

solved COMPARABLE – How to see if elements from objects are equals?