I\'m trying to compare two objects of the same type (in method doesHave), but I\'ve never got \"true\" returned. Here\'s my code:
private ArrayList
Imagine that you and your wife have twins.
Are they the "same" person? No, they are not. Lets call them twin A and twin B. They are two different instances, yes, they look same, but if you are talking twin A, you are not talking about twin B and vice versa. The point is, they are not EQUAL :), it is same in Java. Twin A is equal only to itself, no1 else.
You have to create your own method, which compares all properties of two instances of Osoba.
The other option is to override the equals and hashCode methods, but it is not good approach in your case.
Responds from @libik and @Code Whisperer helped me, so if anyone has the same problem, read and try to understand, it helped for me. I like that twins allegory :) It's kind of the same situation when I tried to compare two Strings.
Right now your code checks if the memory address of two objects is the same which can only be true if it is the same exact object.
You need to implement a method that compares two Osoba
objects by comparing whichever properties you want from these objects and returning true/false
appropriately.
Osaba
should implement equals
:
@Override
public boolean equals(Object other) {
return imie.equals(((Osaba) other).getImie())
&& nazwisko.equals(((Osaba) other).getNazwisko()));
}
If you do not implement equals, the default implementation will be used.