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!