-
It is common to compare an object or its contents directly to equals. By default, these are pointer addresses, but sometimes you need to compare the contents or attributes of two objects.
-
If you want to compare two objects to equals (), you can override the equals () method of the Object.
-
Person. Java class object
Public class Person {// Object attribute String name; int age; Public Person (String name, int age) {this.name = name; this.age = age; Override public Boolean equals(Object obj) {return super.equals(Object obj); If (this == obj) {return true; } / / whether the same class if (obj = = null | | getClass ()! = obj.getClass()) { return false; } Person p = (Person)obj; // compare content if (age! = p.age) { return false; } if (name ! = p.name) { return false; } // return true; }}Copy the code
-
Main.java entry function
Public class test {public static void main(String[] args) {Person p1 = new Person(); Person p2 = new Person(); // Person p1 = new Person("dzm", 20); // Person p2 = new Person("xyq", 20); Println (p1 == p2); system.out.println (p1 == p2); // system.out.println (p1.equals(p2)); Println (p1.equals(p2)) = system.out.equals (p2); }}Copy the code