Java Reference
In-Depth Information
The above method is one of the many ways, not the only way, to compute hash code of an object in Java. Consult
a good textbook on computing hash codes if you need a stronger hash function. All primitive wrapper classes and
String class override the hashCode() method to provide reasonably good implementations of hash functions.
java 7 added a utility class java.lang.Objects . It contains a hash() method that computes the hash code for
any number of values of any type. From java 7, you are advised to use the Objects.hash() method to compute the hash
code of an object. please refer to “the Objects Class” section later in this chapter for more details.
Tip
Listing 7-1 contains the code for a Book class. It shows one of the possible implementations of the hashCode()
method.
Listing 7-1. A Book Class That Reimplements the hashCode() Method
// Book.java
package com.jdojo.object;
public class Book {
private String title;
private String author;
private int pageCount;
private boolean hardCover;
private double price;
/* Other code goes here */
/* Must implement the equals() method too. */
public int hashCode() {
int hash = 37;
int code = 0;
// Use title
code = (title == null ? 0 : title.hashCode());
hash = hash * 59 + code;
// Use author
code = (author == null ? 0 : author.hashCode());
hash = hash * 59 + code;
// Use pageCount
code = pageCount;
hash = hash * 59 + code;
// Use hardCover
code = (hardCover ? 1 : 0);
hash = hash * 59 + code;
 
 
Search WWH ::




Custom Search