Comparing objects never returns true

后端 未结 4 1877
死守一世寂寞
死守一世寂寞 2021-01-25 20:35

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          


        
相关标签:
4条回答
  • 2021-01-25 21:16

    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.

    0 讨论(0)
  • 2021-01-25 21:17

    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.

    0 讨论(0)
  • 2021-01-25 21:27

    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.

    0 讨论(0)
  • 2021-01-25 21:27

    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.

    0 讨论(0)
提交回复
热议问题