Sunday, May 12, 2019

HashMap

Java HashMap class
HashMap is a  part of java.util package in Java's collection, since Java 1.2. HashMap is the basic implementation of Map interface of Java. It contains the data in (Key, Value) pairs. Its implements the Map interface and extends AbstractMap class. It also implements Cloneable and Serializable interface
  • It contains only unique elements i.e doesn’t allow duplicate keys.
  • It can have only one null key and multiple null values.
  • It not maintains the order of insersion i.e. unordered collection.
  • It does not guarantee any specific order of the elements.
  • Initial Capacity is 16
  • Load Factor is 0.75
  • HashMap double the size while reach threshold value.
  • Java HashMap is not thread-safe.
  • Iterators of HashMap class are fail-fast.
  • All Implemented Interfaces: Serializable, Cloneable, Map<K,V>
  • Direct Known Subclasses: LinkedHashMap, PrinterStateReasons

HashMap Class Methods
There are some most useful methods of Map interface.
  1. value put(Key k, Value v): add the key value pairs into the map. if adding key and value pair first time than return null and if adding same key with different value than return old value.
  2. Value get(Object key): It returns value for a specified key.
  3. void clear(): It removes all the elements from the specified Map.
  4. Object clone(): It returns a copy of a map and used for cloning them into another map.
  5. boolean containsKey(Object key): its return a boolean value true or false based on whether the specified key is found in the map.
  6. boolean containsValue(Object Value): Similar to containsKey() method, its use for the specified value instead of key.
  7. boolean isEmpty(): It used to check whether the map is empty. If there is no key-value pairs present in the map then returns true else false.
  8. Set keySet(): It returns the Set of the keys fetched from the map.
  9. int size(): Returns the size of the map i.e. number of key-value pairs in map.
  10. Collection values(): It returns a collection of values of map.
  11. Value remove(Object key): It removes the key-value pair for the specified key. 
  12. void putAll(Map m): Copies all the elements of a map to the another specified map.
  13. Collections.synchronizedMap(): Use to obtain a synchronized view of the HashMap.
Initial Capacity: Initial Capacity is the capacity of HashMap instance when it is created.

Load Factor: Load Factor is a measurement factor, which decides when exactly to increase the hashmap capacity(buckets) and rehashed the hashmap. Default load factor of Hashmap is 0.75f (i.e 75% of current map size).

Rehashing: Rehashing is a process of increasing the capacity of hashMap means once hashMap reached to threshold value. hashMap increase there capacity by rehsahing.In HashMap capacity is multiplied by 2
threshold value = initial size * load factor
if inital size is 16 than
Threshold value = 16*0.75 = 12 i.e. once we try to add 13th element in hashMap then it need to Rehashing to hashMap.

Hash Collision: If hashCode of two different keys are same (i.e means bucket location is also same). which can happen because two unequal objects (In Java can have the same hashCode. this is called hash collision.

Q- What is the difference in hashmap implementation in Java 7 and 8 ? 

Q- What is contract of hashcode and equals in java?
Answer: 
1) if two object are equal using equals() methods then their hashCode() should be same.
object1.equal(object2) then object1.hashCode() == object2.equals() should be true. 

2) If hashCode() of two object are equal than object are equals may not true.
object1.hashCode() == object2.equals() then object1.equal(object2) may not true, does not guarantee. 

Q- How to iterate Map in Java?
The following different ways of iterating over a HashMap -
  • Iterating over Map.entrySet() using simple for-each loop.
  • Iterating over keys or values using keySet() and values() methods
  • Iterating using iterators over Map.Entry<K, V>
  • Using forEach(action) method :
  • Iterating over keys and searching for values (inefficient)
  • Iterating over a HashMap using Java 8 forEach and lambda expression.
  • Iterating over the HashMap’s entrySet using Java 8 forEach and lambda expression.
Q- How HashMap Generate hashCode()?
The java.lang.String.hashCode() method returns a hash code for  string. The hashcode for a given String object is computed as following formula

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 

where, s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation

package com.javaiq.in.example;

public class HashcodeComputation {

 public static void main(String[] args) {
  String str1 = "ABCD";
  System.out.println("Hash Code of ABCD by hashCode() method :- " + str1.hashCode());

  HashcodeComputation hashTest = new HashcodeComputation();
  int genHash = hashTest.generateHashCode(str1);
  System.out.println("Hash Code of ABCD by hashCode() generateHashCode() method : " + genHash);

  String str2 = "BADC";
  System.out.println("Hash Code Of BADC :" + str2.hashCode());
 }

 public int generateHashCode(String string) {
  int hash = 0;
  char[] strArr = string.toCharArray();
  int n = string.length();
  int count = 1;
  for (char ch : strArr) {
   int ascii = (int) ch;
   hash += ascii * Math.pow(31, n - count);
   count++;
  }
  return hash;
 }
}

Q- Is hashCode() of ABCD and BADC same?
Answer: No, as mention above example?




Related Tutorials 

No comments:

Post a Comment