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

前端 未结 15 1219
礼貌的吻别
礼貌的吻别 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{
    
        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");
            }
        }
    }
    

提交回复
热议问题