Ed Lee
Ed Lee

Reputation: 417

Hashcode of an int

What is the hashcode of a primitive type, such as int?

for example, let's say num was an interger.

int hasCode = 0;

if (num != 0) {
  hasCode = hasCode + num.hashCode();
}

Upvotes: 40

Views: 68979

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200138

For the hashCode of an int the most natural choice is to use the int itself. A better question is what to use for the hashCode of a long since it doesn't fit into the int-sized hashcode. Generally, your best source for that—and all hashCode-related questions—would be Effective Java.

Here's what Effective Java recommends (and the JDK uses) for the long type:

(int) (value ^ (value >>> 32))

Upvotes: 50

Amogh Mishra
Amogh Mishra

Reputation: 1238

The java.lang.Integer.hashCode() method returns a hash code value for primitive value of int but represented as an Integer object.

/**
 * Returns a hash code value for an Integer,
 * equal to the primitive int value it represents.
 */
public class IntegerDemo {

    public static void main(String[] args){
        Integer i = new Integer("20");
        System.out.println("Value = " + i.hashCode());
    }

}`

Results:

Value = 20

Source Link: http://www.tutorialspoint.com/java/lang/integer_hashcode.htm

Upvotes: 1

kosa
kosa

Reputation: 66637

No hashCode() method for primitive type int available.

Integer is Wrapper class type and hashcode() returns an int

Upvotes: 9

Konrad Reiche
Konrad Reiche

Reputation: 29483

Taken from the Integer.class source code:

/**
 * Returns a hash code for this {@code Integer}.
 *
 * @return  a hash code value for this object, equal to the
 *          primitive {@code int} value represented by this
 *          {@code Integer} object.
 */
public int hashCode() {
    return value;
}

Where value is the value of the integer.

Upvotes: 48

Related Questions