Object comparison for equality : JAVA

前端 未结 4 1096
野性不改
野性不改 2020-12-21 14:20
public ClassA
{
private String firstId;
private String secondId;

public void setFirstId(String firstId) {
           this.firstId = firstId;
   }


   public String         


        
相关标签:
4条回答
  • 2020-12-21 14:40

    What you are trying to do here in not correct. The 2 objects that you are comparing are not only different objects but are also of different types (ClassA and ClassB) which have no relational at all.

    Moreover if you try to compare like this

    if(bList.contains(clsA))
    

    As your bList contains objects of type ClassB and clsA is of type ClassA, they will be compared using java.lang.Object class's equals() method. So x.equals(y) returns true if and only if x and y refer to the same object (x == y has the value true).

    0 讨论(0)
  • 2020-12-21 14:43

    With the default implementation of Object.equals, two objects of different classes will never be the same.

    If you want that behavior, you will need to override .equals in your classes (and .hashcode as well, look at the javadoc).

    (Or make a comparator and pass it to your collections).

    0 讨论(0)
  • 2020-12-21 14:43

    You can implement a compareTo(ClassB) or even a compareTo(CommonInterfaceOrSuperclass) method in each that will do the field-level comparison and return true if they meet your comparison criteria. You would then need to iterate over your lists and check against each element.

    Another alternative is to implement the equals()/hashcode() pair, which would, when coded properly, allow your List to find and compare for equals-ness successfully. Your contains() test would then work.

    0 讨论(0)
  • 2020-12-21 14:52

    Eventhough content is same they are different objects which doesn't satifsy equal condition. You may need to do explicit a.getfirstId().equals(b.getfirsId()) and a.getscondID().equals(b.getSecondId()) by iterating.

    The other possibility may be overriding equals and hashcode methods in both POJO classes. Refer this link for equals/hashcode contract.

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