java compare objects by value (equals method example)
Java[Edit]
+
0
-
0
Java compare objects by value (equals method example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52// Student.java file: import java.util.Objects; public static class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } public int getId() { return this.id; } public String getName() { return this.name; } @Override public boolean equals(Object object) { // <----------- equals let's to compare objects by value if (object == null) return false; if (object == this) return true; // if same references if (object instanceof Student) { Student student = (Student) object; return Objects.equals(this.id, student.id) && Objects.equals(this.name, student.name); } return false; } } // Program.java file: public class Program { public static void main(String[] args) { Student a = new Student(1, "John"); Student b = new Student(2, "Matt"); Student c = new Student(2, "Matt"); boolean result1 = a.equals(b); // false boolean result2 = a.equals(c); // false boolean result3 = b.equals(b); // true boolean result4 = b.equals(c); // true } }