Search code examples
javalistarraylistcomparelist-comparison

Java - Equals list returning false?


I have this code that compares if the two lists have the same objects:

List<CcustoPrestadorOuImplDTO> implsNaConfig = configImplPermitida.getImplementos();
List<CcustoPrestadorOuImplDTO> implsNoApto = configuracaoImplementoDoApontamento.getImplementos();
Collections.sort(implsNaConfig, Comparator.comparing(o -> o.getCdCcusto()));
Collections.sort(implsNoApto, Comparator.comparing(o -> o.getCdCcusto()));

if ( implsNaConfig.equals(implsNoApto)  ){
    return true;
}

In debbuging I have this situation:

enter image description here

As you can see, both lists have the same object with the same properties.

But the code that compares if the two lists are equals its always returning false.

I tried with containsAll() method but for some reason returns false too.

What am I doing wrong?


Solution

  • As @DawoodibnKareem asked, I will post the solution:

    The reason for always getting "false" in the if ( implsNaConfig.equals(implsNoApto) ) its because my CcustoPrestadorOuImplDTO class didn't have the equals method implemented.

    So I edited the class file and auto-generated the equals method and it worked.

    The equals method in the CCustoPrestadorOuImplDTO class:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CcustoPrestadorOuImplDTO that = (CcustoPrestadorOuImplDTO) o;
        return Objects.equals(cdCcusto, that.cdCcusto) &&
                Objects.equals(deCcusto, that.deCcusto) &&
                Objects.equals(grupoOperativo, that.grupoOperativo) &&
                Objects.equals(deGrupoOperativo, that.deGrupoOperativo);
    }
    

    And this is the HashCode() method:

    @Override
    public int hashCode() {
    
        return Objects.hash(cdCcusto, deCcusto, grupoOperativo, deGrupoOperativo);
    }
    

    It's really simple, but I did not even think that this was the cause of the issue.

    Thank you everybody.