Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Methods in Java's Object Class

Tech 1

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 == d is true).
    • For references, it checks if both variables point to the same memory address (i.e., the same object).
  • 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():

  1. It enhances performance in hash-based collections like HashMap or HashSet.
  2. If two references point to the same object, their hash code are identical.
  3. The converse isn’t guaranteed: equal hash codes don’t imply the same object.
  4. 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 + "'}";
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.