-1

I have been trying to use the equals() method and == with two Baby objects but both gave me false.

public class Baby {
    String name;

    Baby(String myName) {
        name = myName;
    }

    public static void main(String[] args) {
        Baby s1 = new Baby("a");
        Baby s2 = new Baby("a");
        System.out.println(s2.equals(s1));
        System.out.println(s1 == s2);
    }

}
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
creative creative
  • 455
  • 1
  • 6
  • 12

4 Answers4

7

Your output is correct: s1 does not in fact equal s2 if you use the == operation since they are distinct separate instances, which is exactly what == checks for. Since Baby does not override the equals method, a call to it will default to the == operation, returning false. Instead you should have your class override the public boolean equals(Object o) method and call it when needed.

public class Baby {
   String name;

   Baby(String myName) {
      name = myName;
   }

   @Override
   public int hashCode() {
      final int prime = 31;
      int result = 1;
      result = prime * result + ((name == null) ? 0 : name.hashCode());
      return result;
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      Baby other = (Baby) obj;
      if (name == null) {
         if (other.name != null)
            return false;
      } else if (!name.equals(other.name))
         return false;
      return true;
   }

   public static void main(String[] args) {
      Baby s1 = new Baby("a");
      Baby s2 = new Baby("a");
      System.out.println(s2.equals(s1));
      System.out.println(s1 == s2);
   }


}

Oh, and don't forget to override hashCode() as well so you don't have two objects being equal but having two different hashCodes -- not kosher!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

s1 == s2 will only evaluate to true if s1 and s2 are the same object. They are not in your case. They are different objects although the contents may be identical.

The .equals method (if implemented correctly; that's your job) compares the contents and therefore, in your case, will return true.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Unless you override equals, it will tell you that s1 and s2 are indeed distinct objects. They are 2 distinct babies that just happen to have the same name. :)

theglauber
  • 28,367
  • 7
  • 29
  • 47
0

See this question: What is the difference between == vs equals() in Java?

which explains the difference between == and using the .equals() method.

Or this helpful video.

Community
  • 1
  • 1
Jon Lin
  • 142,182
  • 29
  • 220
  • 220