Concept
How do equals() and hashCode() define object equality in Java?
ComputerScienceOne / Common Methods
"Two other methods, the equals() and the hashCode() method are used extensively by other classes such as the Collections library. The equals() method:\n\npublic boolean equals(Object obj)\n\ntakes another object obj and returns true or false depending on whether or not the instance is “equal” to obj. Recall that identity is one of the defining characteristics of objects. This method is how Java achieves identity; this method allows you to define what “equality” means. By default, the behavior inherited from the Object class simply checks if the object, this and the passed object, obj are located at the same memory address, essentially (this == obj). However, conceptually we may want different behavior. For example, two Student objects may be the same if they have the same id value (it is, after all supposed to be a unique identifier). Alternatively, we may consider two objects to be the same if every member variable holds the same value. Even with only a four member variables, the logic can get quite complicated, especially if we have to account for null values. For this reason, many IDEs provide functionality to automatically generate such methods.\n\nThe hashCode() method,\n\npublic int hashCode()\n\nreturns an integer representation of the object. As with the equals() method, the default behavior is to return a value associated with the memory address of the instance. In general, however, the behavior should be overridden to be based on the entire state of the object. A hash is simply a function that maps data to a “small” set of values. In this context, we are mapping object instances to integers so that they can be used in hash table-based data structures such as HashSet or HashMap. The hashCode() method is used to map an instance to an integer so that it can be used as an index in these data structures. Again, most IDEs will provide functionality to generate a good implementation for the hashCode() method."
Related Ideas
- What is the relationship between equals() and hashCode()?ComputerScienceOne · Composition
- Why are equals() and hashCode() important when searching and using sets?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- How do Java sets store unordered unique elements?ComputerScienceOne · Dynamic Data Structures
- How do Java collections perform a linear search?ComputerScienceOne · Searching
- What common methods do Java classes inherit?ComputerScienceOne · Usage
- How do you compare strings in Java?ComputerScienceOne · Comparisons
- How can you compare String values in Java?ComputerScienceOne · Tokenizing
- What does the completed Java Student class example contain?ComputerScienceOne · Example