- What is HashCode in Java?
- What is HashCode in Java?
- What is hash code in java
- HashCode() in Java
- Introduction
- The Java hashCode() Method
- Example
- Integer class hashCode Methods in Java
- Declaration of hashCode in Java
- Parameters of the hashCode Method
- Return value of the hashCode Method in Java
- Implementation of hashCode in Java
- Example of hashCode(int value)
- Example of hashCode() method
- Use of hashCode in Hashing
- Conclusion
What is HashCode in Java?
Hash code is an integer returned by hashCode() method. It has many advantages in different applications in java. Let us see how this method is giving hash code, how it is useful and what is the significance in java?
What is HashCode in Java?
Based on hash code we can keep objects in hash buckets. Some algorithms or data structures will use these hash buckets. Mostly hash based data structures like hashmap, hashset, hashtable will use this hash code. hashCode() method is provided by every class is either explicitly or implicitly. It is specified in java.lang.Object class. This method will return an integer as a result by mapping an integer to internal memory address in which object is stored. This hash code is same whenever we called hashCode() method with same object more than once in same execution. But in different execution of same application may give different integer.
Different objects can have same hash code because hash code is 32 bit signed integer. Total number of different possible hash values are 2^32. But total number of different objects can be more than 2^32. So hash code can be repeated. Then collision will happen. In this case we need to select the particular object that we need from that specific hash bucket. Hash buckets will reduce the search space for searching. Too many collisions will decrease the performance.
We can override this function when it is needed. But equals() method must be overridden whenever hashCode() method has been over ridden. This is because whenever two objects are equal according to equals() method then they should return the same hash code. But we can’t say if hash code is same then objects are same. See the below picture for clear understanding.
What is hash code in java
День добрый, уважаемые дамы и господа знатоки. Есть вопрос прикладного характера. В начале объясняется, что прежде сравнения нужно убедиться, что сравниваются объекты одного класса. Это логично и понятно. Соответствующая строка в коде дополняет сказанное. НО! Зачем тогда следующей строкой приводить проверяемый объект к классу объекта-эталона? Если мы и так знаем, что объекты одного класса, иначе до выполнения этой строки не дошло бы — метод прекращается после return, зачем ещё раз приводить их к одному классу? Выглядит дико и просто как пятое колесо. У велосипеда. @Override public boolean equals(Object o) < if (getClass() != o.getClass()) return false; Man man = (Man) o; // Вот это что?? Зачем. return dnaCode == man.dnaCode; >
@Override public boolean equals(Object o) < if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LuxuryAuto that = (LuxuryAuto) o; // а может добавить еще одну проверку ? if (this.hashCode() != o.hashCode()) return false; // например такую ? // тогда псевдо одинаковые обьекты будут не равны при не равных хешах if (manufactureYear != that.manufactureYear) return false; return dollarPrice == that.dollarPrice; >@Override public int hashCode()
последний пример вводит в тупик. При сравнении через equals, сначала проверяются hashCode’ы, если они не равны, то сравнение через equals не последует. В нашем примере как раз таки это и происходит. Как equals показал true, если хэши у них разные и до метода equals код не должен был дойти и сразу дать false?? Теперь поговорим о методе hashCode(). Зачем он нужен? Ровно для той же цели — сравнения объектов. Но ведь у нас уже есть equals()! Зачем же еще один метод? Ответ прост: для повышения производительности. Хэш-функция, которая представлена в Java методом hashCode(), возвращает числовое значение фиксированной длины для любого объекта. В случае с Java метод hashCode() возвращает для любого объекта 32-битное число типа int. Сравнить два числа между собой — гораздо быстрее, чем сравнить два объекта методом equals(), особенно если в нем используется много полей. Если в нашей программе будут сравниваться объекты, гораздо проще сделать это по хэш-коду, и только если они равны по hashCode() — переходить к сравнению по equals().
HashCode() in Java
Hashing is a fundamental Computer Science concept which involves mapping objects or entities to integer values. These values are called hash values or hashcodes of those entities.
The hashCode() method in Java is used to compute hash values of Java objects. The Integer class in Java contains two methods — hashCode() and hashCode(int value) which compute the hash values of Integer objects and primitive int values respectively.
Introduction
In this article, we will learn one of the most fundamental concepts in Computer Science — Hashing in Java. We implement hashing through a method called hashCode in Java.
Hashing is the process of mapping an object or a primitive data type to some representative integer value using hashing algorithms. In Java, a hash code is an integer value that can be computed for all objects. Efficient hashing algorithms are the base of popular collections framework such as HashMap and HashSet in Java.
Properties of Hashing:
- Objects that are equal based on the output of equals() method must have the same hash value, i.e. they must be mapped to the same integer value.
- Two objects which are not equal may or may not have same hash values. Thus, different objects need not have different hash values.
- The hash values of objects must remain consistent when computed multiple times in the same execution cycle.
- The output of hashing algorithms, when invoked for the same object more than once during the execution of a Java application, must remain the same.
- However, this value need not stay consistent from one execution of the Java application to another.
The Java hashCode() Method
The hashCode() method is defined in Java Object class which computes the hash values of given input objects. It returns an integer whose value represents the hash value of the input object.
The hashCode() method is used to generate the hash values of objects. Using these hash values, these objects are stored in Java collections such as HashMap , HashSet and HashTable .
Example
Through this example, we will test the basic properties of Hashing mentioned in the previous section.
- Two objects with the same value have the same hashcodes.
- Objects with different values usually have different hashcodes.
- Hashcodes of the same object when computed more than once must remain the same.
Integer class hashCode Methods in Java
hashCode in Java are of two types based on their respective parameters-
- hashCode() Method — The hashCode() method belongs to the Java Integer class. It returns the hash value of a given Integer object. This method overrides the hashcode() method of the Object class.
- hashCode(int value) Method — This method, which clearly has a parameter, determines the hashcode of its parameter: value .
Declaration of hashCode in Java
The syntax of the two types of hashCode() methods in Java is as follows –
Parameters of the hashCode Method
As we can see, the first type of hashCode method does not have a parameter.
The second type of hashCode method has the following parameter-
Return value of the hashCode Method in Java
The return value of the two types of hashCode method in Java are as follows-
Method | Return Value |
---|---|
hashCode() | Returns the hashcode of the calling Integer object. The hashcode is computed using the primitive int value represented by the Integer object. |
hashCode(int value) | This method returns the hashcode of its primitive int argument i.e. value . |
Implementation of hashCode in Java
Now that we are done with learning about the different types of hashCode() methods in Java and their syntax and parameters, let’s implement them in an example.
Example of hashCode(int value)
Example of hashCode() method
Now let’s take a look at how to compute the hashCode of Integer objects in Java.
Use of hashCode in Hashing
For our advanced learners, we can take a look at how hashCode in Java is employed in HashMaps to compute the hash value of the HashMap keys.
- HashMap is a part of collections framework in Java.
- When we store a (key, value) in a HashMap, the hashcode of the key is calculated. The hashcode value received is referred to as a bucket number.
- Keys with the same hash code are present in the same bucket. In the same bucket, multiple (key, value) pairs may be stored in the form of a linked list.
- However keys with different hash codes reside in different buckets.
- When we access the value associated with a particular key, the hashcode of the key is computed again.
- This hashcode value is used to refer to its bucket and the corresponding value is retrieved from it.
Conclusion
- Hashing is a Computer Science concept that maps an object or entity to an integer.
- The hash value of an object is an integer value that is computed using the properties of that object.
- Every object in Java inherits the hashCode() and equals() method.
- Hash codes of two equal objects must be the same. However, the hash codes of two unequal objects need not be distinct.
- An efficient hashing algorithm generates distinct hashcodes for unequal objects.
- The hashCode method should be consistent in its implementation of the equals() function.
- hashCode() and hashCode(int value) methods, defined in the Integer class, compute the hash codes of integer objects or values in Java.