This came up in class the other day.
Expressions involving the comparison operator (==) and two object references return true if the operands point to the same object. If you want to make a more meaningful comparison you have to override the equals method that all objects inherit from java.lang.Object.
See the Java code below to see how to override the equals method.
public class EqualityDemo { public static void main(String[] args) { Student s = new Student("Fred", 123); Student t = s; Student u = new Student("Fred", 123); System.out.println(s==t); System.out.println(s==u); System.out.println(s.equals(u)); } } class Student { String name; int id; public Student(String name, int id) { this.name = name; this.id = id; } @Override public boolean equals(Object object) { Student student = (Student)object; return this.id == student.id && this.name.equalsIgnoreCase(student.name); } }
Output: true false true