in java obj.hashcode() return some value i want to know what is the use of hash code? in java.please answer me.
Five answers:
Light Cloud
2010-08-25 00:50:31 UTC
hashCode is used in the HashSet and HashMap (in java.util.* as part of Java's Collections library).
If you're familiar with hash tables, you know that in order to store objects, we need a hashing function to decide which bucket to put the object in. Java uses hashCode() as the hashing function.
The most important consequence is that if you override the equals() method, you must also override the hashcode() method to ensure that it's consistent. In particular, two objects that are equal must have the same hashcode().
HMJava
2010-08-26 12:48:06 UTC
I will answer in plain english
Basically what hashcode does is it takes a string such as a word "bob" and it returns the number representation of the string
lets say b = 3
o = 6
then "bob" will be 3+3+6 = 12
so the hash code of bob will be 12.
http://www.homeworkjava.com
deonejuan
2010-08-25 00:08:58 UTC
think of hashcode as a cache. If an Object is made up of String, an Integer, another Object, and a Boolean -- hashcode would cache the Objects.
The built-in Java API Objects such as Boolean, Long, Integer, String and some others (note the capital letter) have methods hashcode(); equals(); compare(); compareTo(); written for you. Unless you extend one of those Objects you will have to write your own code for compareTo(); which will help you sort Objects.
compareTo() returns an integer result. -1 if less than current; 0 if the same; 1 or greater than the current Object -- sometimes compareTo() returns the 'offset distance' of the sorted Objects. Very useful.
anonymous
2016-04-20 02:35:44 UTC
public int hash(String key, int capacity) { int result = 1; for( int i = 0 ; i < key.length() ; ++i) result *= key[i]; return result % capacity; } That multiplies all the ASCII codes together, giving a hash number for the sane string every time.