Compare two objects with .equals() and == operator

前端 未结 15 1208
礼貌的吻别
礼貌的吻别 2020-11-22 01:13

I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too

相关标签:
15条回答
  • 2020-11-22 01:36

    the return type of object.equals is already boolean. there's no need to wrap it in a method with branches. so if you want to compare 2 objects simply compare them:

    boolean b = objectA.equals(objectB);
    

    b is already either true or false.

    0 讨论(0)
  • 2020-11-22 01:37

    The "==" operator returns true only if the two references pointing to the same object in memory. The equals() method on the other hand returns true based on the contents of the object.

    Example:

    String personalLoan = new String("cheap personal loans");
    String homeLoan = new String("cheap personal loans");
    
    //since two strings are different object result should be false
    boolean result = personalLoan == homeLoan;
    System.out.println("Comparing two strings with == operator: " + result);
    
    //since strings contains same content , equals() should return true
    result = personalLoan.equals(homeLoan);
    System.out.println("Comparing two Strings with same content using equals method: " + result);
    
    homeLoan = personalLoan;
    //since both homeLoan and personalLoan reference variable are pointing to same object
    //"==" should return true
    result = (personalLoan == homeLoan);
    System.out.println("Comparing two reference pointing to same String with == operator: " + result);
    

    Output: Comparing two strings with == operator: false Comparing two Strings with same content using equals method: true Comparing two references pointing to same String with == operator: true

    You can also get more details from the link: http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html?m=1

    0 讨论(0)
  • 2020-11-22 01:38

    It looks like equals2 is just calling equals, so it will give the same results.

    0 讨论(0)
  • 2020-11-22 01:38

    Statements a == object2 and a.equals(object2) both will always return false because a is a string while object2 is an instance of MyClass

    0 讨论(0)
  • 2020-11-22 01:42

    The overwrite function equals() is wrong. The object "a" is an instance of the String class and "object2" is an instance of the MyClass class. They are different classes, so the answer is "false".

    0 讨论(0)
  • 2020-11-22 01:43

    When we use == , the Reference of object is compared not the actual objects. We need to override equals method to compare Java Objects.

    Some additional information C++ has operator over loading & Java does not provide operator over loading. Also other possibilities in java are implement Compare Interface .which defines a compareTo method.

    Comparator interface is also used compare two objects

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