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 has constant-time performance O(1) for most operations like put(), get(), remove() and contains().
HashMap Class Methods
There are some most useful methods of Map interface.
- 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.
- Value get(Object key): It returns value for a specified key.
- void clear(): It removes all the elements from the specified Map.
- Object clone(): It returns a copy of a map and used for cloning them into another map.
- boolean containsKey(Object key): its return a boolean value true or false based on whether the specified key is found in the map.
- boolean containsValue(Object Value): Similar to containsKey() method, its use for the specified value instead of key.
- 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.
- Set keySet(): It returns the Set of the keys fetched from the map.
- int size(): Returns the size of the map i.e. number of key-value pairs in map.
- Collection values(): It returns a collection of values of map.
- Value remove(Object key): It removes the key-value pair for the specified key.
- void putAll(Map m): Copies all the elements of a map to the another specified map.
- 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).
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 ?
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
- Java Collections Interview
- List Interface In Java
- ArrayList
- LinkedList
- Custom Own ArrayList Implementation
- Custom LinkedList implementation in java
- Set Interface In Java
- Map Interface In Java
- HashMap In Java
- TreeMap
- HashMap Vs ConcurrentHashMap
- HashMap Vs HashTable In Java
- HashMap Vs HashSet In Java
- HashMap Vs TreeMap In Java
- HashMap vs LinkedHashMap In Java
- TreeSet Vs TreeMap In Java
- SortedSet Vs TreeSet In Java
- SortedMap Vs TreeMap In Java
- Array Vs ArrayList In Java
- ArrayList Vs LinkedList In Java
- How HashSet Works Internally
- How TreeMap Works Internally
- How HashMap Works Internally
- How ConcurrentHashMap Works Internally
- How To Detect Loop In A LinkedList In Java
- Detect And Remove Loop In A LinkedList
No comments:
Post a Comment