Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Object hashCode() Method

Java Object hashCode() Method

Java String ClassJava Object Class


The Object hashCode() method is used to obtain the hash value of an object.

Syntax


object.hashCode()

Parameters

Return Value

Returns the object's hash value, an integer representing its position in the hash table.

Example

The following example demonstrates the use of the hashCode() method:

Example

class

RunoobTest

{

public

static

void

main

(

String

[

]

args

)

{

//

Object uses hashCode()

Object

obj1

=

new

Object

(

)

;

System

.

out

.

println

(

obj1

.

hashCode

(

)

)

;

Object

obj2

=

new

Object

(

)

;

System

.

out

.

println

(

obj2

.

hashCode

(

)

)

;

Object

obj3

=

new

Object

(

)

;

System

.

out

.

println

(

obj3

.

hashCode

(

)

)

;

}

}

The execution result of the above program is:


225534817
1878246837
929338653

The String and ArrayList classes use the hashCode() method; both inherit from Object, so they can use the hashCode() method directly:

Example

import

java

.

util

.

ArrayList

;

class

RunoobTest

{

public

static

void

main

(

String

[

]

args

)

{

//

String uses hashCode()

String

str

=

new

String

(

)

;

System

.

out

.

println

(

str

.

hashCode

(

)

)

;

//

0

//

ArrayList uses hashCode()

ArrayList

<

Integer

list

=

new

ArrayList

<>

(

)

;

System

.

out

.

println

(

list

.

hashCode

(

)

)

;

//

1

}

}

The execution result of the above program is:


0
1

The following example demonstrates that if two objects are equal, their hash values are also equal:

Example

class

RunoobTest

{

public

static

void

main

(

String

[

]

args

)

{

//

Object uses hashCode()

Object

obj1

=

new

Object

(

)

;

//

Assign obj1 to obj2

Object

obj2

=

obj1

;

//

Determine whether the two objects are equal

System

.

out

.

println

(

obj1

.

equals

(

obj2

)

)

;

//

true

//

Get the hash values of obj1 and obj2

System

.

out

.

println

(

obj1

.

hashCode

(

)

)

;

//

225534817

System

.

out

.

println

(

obj2

.

hashCode

(

)

)

;

//

225534817

}

}

The execution result of the above program is:


true
225534817
225534817

Java String ClassJava Object Class