
It does not maintain any order which means the order in which data is inserted is not the same as the order in which it is retrieved.Does not allow duplicate keys but can have duplicate values.Stores values corresponding to each key.Eg: String or Integer HashMap Featuresīelow are the features of HashMap in Java: ValueType – It is the type of value data. KeyType – It is the type of key data.Eg: String or Integer The syntax is as given below: HashMap map = new HashMap()

To use HashMap in Java, we need to import package.

In hashing, we use hash functions to link key and value in a HashMap. HashMap in Java works on the principle of hashing technique. Pin HashMap structure and working principle The HashMap class in Java extends the Abstract class AbstractMap and implements the Map interface as shown below.
#HASHMAP JAVA CODE#
Here, the key values of hashmap are converted to integer and the hash code is printed. This is overridden by another function named ‘hashCode’. } Output The hash code for key : This = 84Ī class named ‘hash_map’ defines a string and a constructor. ("The value for key 'sample' is: " + my_map.get(new hash_map("sample"))) ("The value for key 'a' is: " + my_map.get(new hash_map("a"))) ("The value for key 'is' is: " + my_map.get(new hash_map("is"))) ("The value for key 'this' is : " + my_map.get(new hash_map("This"))) ("The hash code for key : " + key + " = " + hash) The formula to find the index of the array is − Index = hashCode(key) & (n-1) – Here n refers to number of buckets. This function returns true or false depending on whether the two objects in questions are equal or not.Īn index value is generated so that the size of array is not big, thereby avoiding outOfMemoryException. This function can be overridden in the customized class by providing customized implementation. The function ‘equals’ is used to check the equality between two objects. Capacity = number of buckets * load factor The capacity of the hashmap can be calculated using the bucket and load factor. The nodes can be connected using linked list data structure. There can be more than two nodes in a single bucket.

It is an element that is used to store nodes. Since we have mentioned ‘bucket’, it is important to understand what it means. It is defined in the following way − public native hashCode() Basically, this function is used to calculate the bucket and index values.

It is a native function, which means no direct method in Java can be used to fetch the reference of the object.įor better performace of HashMap, use the hashCode() properly. It returns the object reference’s memory as an integer. The function ‘hashCode’ is used to get the hash code of an object in Java.
