Core Methods in Java's Object Class
equals Method
The == operator and the equals() method serve different purposes:
-
==works with both primitive and reference types.- For primitives, it compares actual values (e.g.,
int i = 10; double d = 10.0;→i == distrue). - For references, it checks if both variables point to the same memory address (i.e., the same object).
- For primitives, it compares actual values (e.g.,
-
equals()is only applicable to reference types. By default, it behaves like==, comparing object identity. However, many classes overrride it to compare logical equality based on content.
Example from String:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String other = (String) anObject;
if (coder() == other.coder()) {
return isLatin1()
? StringLatin1.equals(value, other.value)
: StringUTF16.equals(value, other.value);
}
}
return false;
}
Example from Integer:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer) obj).intValue();
}
return false;
}
hashCode Method
Key points about hashCode():
- It enhances performance in hash-based collections like
HashMaporHashSet. - If two references point to the same object, their hash code are identical.
- The converse isn’t guaranteed: equal hash codes don’t imply the same object.
- The hash code is derived from the object’s internal address but is not the address itself.
public class HashCodeDemo {
public static void main(String[] args) {
AA x = new AA();
AA y = new AA();
AA z = x;
System.out.println(x.hashCode()); // e.g., 1967205423
System.out.println(y.hashCode()); // e.g., 42121758
System.out.println(z.hashCode()); // same as x: 1967205423
}
}
class AA {}
toString Method
The default toString() implementation in Object returns a string composed of the fully qualified class name and the hexadecimal representation of the object’s hash code:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
When an object is printed or concatenated in a string context, toString() is automatically invoked. Classes often override this method to provide meaningful output:
public class ToStringDemo {
public static void main(String[] args) {
Monster creature = new Monster("小猪妖", "巡山");
System.out.println(creature); // Uses overridden toString()
}
}
class Monster {
private String name;
private String role;
public Monster(String name, String role) {
this.name = name;
this.role = role;
}
@Override
public String toString() {
return "Monster{name='" + name + "', job='" + role + "'}";
}
}