Daniel Pereira Daniel Pereira - 25 days ago 13
Java Question

Java boolean equals method with ArrayLists

I have a Class named

Produto
and a Class named
Fatura
, the last one have a
private long nif
and a
private ArrayList<Produto> lista = new ArrayList<Produto>();


On my
equals()
method I have:

public boolean equals (Object o) {
if (o != null && this.getClass() == o.getClass()) {
Fatura f = (Fatura) o;
return (this.nif == f.nif && f.lista.equals(o));
}
return false;
}


On my
Main_test
I create three
Produto
s. Then I create two
Fatura
s. I add the
Produto
s to the
ArrayList
and I set
fatura1
to
fatura2
:

fatura1 = fatura2;


I then call the
equals()
method to see if
fatura1
equals
fatura2
but it returns
false
I don't know why. It should return
true
because they are the same, they have the same
nif
and the same
ArrayList
.

Thanks

Answer

I think the problem is here:

f.lista.equals(o)

You are not passing the right argument to equals. Do this:

f.lista.equals(this.lista) 
Comments