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

前端 未结 15 1209
礼貌的吻别
礼貌的吻别 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:48

    Your class might implement the Comparable interface to achieve the same functionality. Your class should implement the compareTo() method declared in the interface.

    public class MyClass implements Comparable<MyClass>{
    
        String a;
    
        public MyClass(String ab){
            a = ab;
        }
    
        // returns an int not a boolean
        public int compareTo(MyClass someMyClass){ 
    
            /* The String class implements a compareTo method, returning a 0 
               if the two strings are identical, instead of a boolean.
               Since 'a' is a string, it has the compareTo method which we call
               in MyClass's compareTo method.
            */
    
            return this.a.compareTo(someMyClass.a);
    
        }
    
        public static void main(String[] args){
    
            MyClass object1 = new MyClass("test");
            MyClass object2 = new MyClass("test");
    
            if(object1.compareTo(object2) == 0){
                System.out.println("true");
            }
            else{
                System.out.println("false");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:51

    The best way to compare 2 objects is by converting them into json strings and compare the strings, its the easiest solution when dealing with complicated nested objects, fields and/or objects that contain arrays.

    sample:

    import com.google.gson.Gson;
    
    
    Object a = // ...;
    Object b = //...;
    String objectString1 = new Gson().toJson(a);
    String objectString2 = new Gson().toJson(b); 
    
    if(objectString1.equals(objectString2)){
        //do this
    }
    
    0 讨论(0)
  • 2020-11-22 01:53

    Your equals2() method always will return the same as equals() !!

    Your code with my comments:

    public boolean equals2(Object object2) {  // equals2 method
        if(a.equals(object2)) { // if equals() method returns true
            return true; // return true
        }
        else return false; // if equals() method returns false, also return false
    }
    
    0 讨论(0)
提交回复
热议问题