Object comparison in Java is done by its reference, the == operator compares the reference address, and the equals() method compares the object content. For primitive types, equals() compares values, while for reference types, equals() typically compares for content equality, such as String's value property comparison. When using ==, two different objects will return false even if they have the same content; when using equals(), the same content of different objects will return true, such as comparing two Person objects.
Comparison of Java Objects: Mechanism and Practice
In Java, objects can be compared by their references. An object reference represents the address where an object is stored in memory. When we compare two object references, we are actually comparing whether the objects they refer to are the same.
== and equals() method
Java provides two ways to compare objects:
==
== operator is relatively simple, it directly compares the addresses of two references. Two references are equal if they point to the same object.
public boolean equals(Object obj) { if (this == obj) { return true; } return false; }
Implementation of equals()
The implementation of the equals() method needs to be different according to different object types. For primitive types (e.g. int, double), equals() compares their values. For reference types (e.g. String, ArrayList), equals() usually compares their contents for equality.
The following is an example for comparing two String objects:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof String) { String other = (String) obj; return this.value.equals(other.value); } return false; }
Practical case
Suppose we have a piece of code in which we create Two Person objects:
Person p1 = new Person("John", 25); Person p2 = new Person("John", 25);
When comparing these two objects using the == operator, false will be returned because they are different objects.
System.out.println(p1 == p2); // 输出 false
However, when comparing them using the equals() method, it will return true because their contents are equal.
System.out.println(p1.equals(p2)); // 输出 true
The above is the detailed content of How is Java object comparison implemented?. For more information, please follow other related articles on the PHP Chinese website!