In Java, the equals() method, hashCode(), and the == operator are essential for comparing objects, but they serve different purposes and function in distinct ways.
== Operator
The == operator in Java checks for reference equality. It compares whether two object references point to the same memory location. For primitive types (e.g., int, float), == compares values directly. However, for objects, == only returns true if both references point to the same object instance.
Example:
String s1 = new String("hello");
String s2 = new String("hello"); System.out.println(s1 == s2); // false
In the example above, even though s1 and s2 have the same string content, they are different objects in memory, so == returns false.
equals() Method
The equals() method is used to compare the contents of two objects for equality. By default, the equals() method (inherited from the Object class) checks reference equality, like ==. However, many classes (e.g., String, Integer) override equals() to compare actual content.
Example:System.out.println(s1.equals(s2)); // true
Here, the equals() method compares the string values, so it returns true since both strings contain „hello.“
hashCode() Method
The hashCode() method provides a hash value, an integer representation, of an object. It’s used in hashing-based collections like HashMap, HashSet, and HashTable. When two objects are equal (according to equals()), they must have the same hashCode(), though the reverse isn’t necessarily true. This ensures proper behavior in hash-based collections.
Whenever you override equals(), it’s essential to override hashCode() to maintain the general contract between these two methods.

Hinterlasse einen Kommentar