Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); } 
like image 816
Ed Lee Avatar asked Aug 09 '12 19:08

Ed Lee


People also ask

What is the hashCode of an integer?

The hashcode of an integer is the integer itself.

Does int have hashCode Java?

The hashCode(int value) is an inbuilt Java Integer Class method which determines a hash code for a given int value. This method is compatible with Integer.

What is hashCode () in Java?

hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm. The process of assigning a unique value to an object or attribute using an algorithm, which enables quicker access, is known as hashing.

What is the formula for hashCode?

hashcode() is computed via jvm argument -XX:hashCode=N where N can be a number from [0-5]...


2 Answers

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.

like image 154
Konrad Reiche Avatar answered Oct 03 '22 05:10

Konrad Reiche


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. Your best source for that—and all hashCode-related questions—would be Effective Java.

like image 27
Marko Topolnik Avatar answered Oct 03 '22 07:10

Marko Topolnik