I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too. Here's what I've done:
public class MyClass { String a; public MyClass(String ab) { a = ab; } public boolean equals(Object object2) { if(a == object2) { return true; } else return false; } public boolean equals2(Object object2) { if(a.equals(object2)) { return true; } else return false; } public static void main(String[] args) { MyClass object1 = new MyClass("test"); MyClass object2 = new MyClass("test"); object1.equals(object2); System.out.println(object1.equals(object2)); object1.equals2(object2); System.out.println(object1.equals2(object2)); } } After compile it shows two times false as a result. Why is it false if the two objects have the same fields - "test"?
equalsandequals2: any time you have something of the formif(a) { return true; } else { return false; }you should probably just writereturn a.trueif it is andfalseotherwise. So for instance,if(a.equals(object2)) { return true; } else return falsecould just bereturn a.equals(object2).