HashMap and Object Class:

====================================================================
Object Class:
Before discussing about Object class methods you should know one thing that every class by default extends ‘Object’ class. So you can override its methods.
Methods which you can override:
1) toString()
@Override
public String toString() {
return this.itemName+this.itemsCount;
}
2) equals(Object obj)
@Override
public boolean equals(Object obj) {
if(obj instanceof Price){  //checking that the new object getting created is instance of Price class or different class.
return (((Price)obj).itemName.equals(this.itemName) && (((Price)obj).itemsCount==this.itemsCount)) ;
// ((Price)obj).itemName -> means type casting current obj to Price obj as it is instnce of Price class and getting val of ‘itemName’
// this.itemName -> means getting value of ‘itemName’ from Price class.
}
3)     Hashcode()
@Override
public int hashCode() {
// TODO Auto-generated method stub
return new Integer(this.itemsCount).hashCode()+this.itemName.hashCode();
}

4) Clone()
5) finalize()

====================================================================
toString() method:
-> The wrapper classess like ‘Integer’, ‘Double’ will be having ‘toString()’ method in their calsses.
So you can convert Integer to string using that method which has implementation to convert. That’ll take Integer as input and gives string as output.
eg: Integer i = 10;
String ival = i.toString();
Note that toString() method has the code to convert Integer to String.
You can not overwrite the toString method of Integer class. [you can’t extend Integer class as it is decalred as Final. So you can not overwrite its toString method. This applies to all wrapper classes.]
-> If you want to store your class object as key in map. you can do it, but when you try to print the keys present in the Map then it’ll return the hashcode of address where the class object stored in hash memory, insted returning exact key. So you need to overwrite the ‘toString()’ method to give your own implementaion. By default toString method returns hashcode, so by overwriting this method in your class you can return any value for the class object instead of its hashcode.
Go thorugh post for detailed explanation:

====================================================================
hashcode() & equals(Object obj) methods:

  • In your hashmap if your key is String or any wrapper class type then if you insert record like hm.put(“fruit”,”banana”) and again if you insert record like hm.put(“fruit”,”apple”), then the second record’s value will be overridden on existing record, it won’t create new record. Because all the wrapper classes implements (Object class) hashcode() and equals(Object obj) methods. So when you insert a record whose key of wrapper class type, first hashcode() method will be called where the hashcode of key will be generated and checked with existing hashcodes of buckets and if it finds any similar hashcode present for any key then it’ll call equals method. In equals method it matches the current key with the matched hashcode key and if the Key’s are also same then returns boolean ‘True’. If it returns true then it will override the existing record, instead creating a new record.
  • Suppose your hashmap is using the key of custom type instead of wrapper class type like below HashMap<Price, int>hm = new HashMap<>(); In this case Key ‘Price’ class is not a wrapper class, so by default it won’t implement equals and hashcode methods. So if you insert a record even though the keys are same it’ll create a new record instead overriding the existing record. So you have to manually override the hashcode() and equals(Object obj) methods. In those method write the logic to generate the hashcode in hashcode() method and logic to compare Keys in equal method.

Now let’s discuss about equals() method. Lets take an example to understand about this method. You have an HashMap and you are storing the class object as Key and value as String. HashMap allows you to insert duplicate Keys(If your key is not of wrapper class type). If your requirement is like not to allow duplicate Keys then you must have to override equals(Object obj) method along with Hashcode() method and put your own implementation. Why? As shown in above example code snippets, first hashcode method will be triggered in which we are manually assigning hashcode to the key. after hashcode()  method, if the same hashcode generated is already present in bucket then equals(Object obj) method will be triggered. In equals(Object obj) method we are comparing current key object getting inserted is an instance of Price class, If yes then compare current object is already exists in HashMap or not, if yes return True. If you return true in equals method, then it’ll assign the new value to the existing key instead creating a new key value pair in HashMap.

====================================================================
HashMap vs Concurrent Hashmap:
Assume HashMap has a bucket and all the contents(Key Value pairs) are stored in it in one of the 16 slots based on Key’s hash value.
Let’s take a scenario, if many threads are acessing same Hashmap and if one thread is trying to modify the HashMap data(Key) and if another thread trying to read the data from HashMap then it’ll get ‘ConcurrentModificationException’. So to avoid this we can use ConcurrentHashMap which is synchronized. By using ConcurrentHashMap the same instance is cloned/shared by all the threads. So if the key is changed in one thread, then its newly generated Hashcode(address in bucket) is automatically updated in all the threads.
Note: You can synchronize your method also, but using Concurrent Hashmap is preferred over this as only HashMap is synchronized rather than everything in mehtod. And another thing you have to understand is that performance will be decreased when using ConcurrentHashMap as it updates latest records in all the current threads (which depends on number of users accessing the HashMap).
-> When you’ve multiple threads which try to modify data in HashMap, then  (1) use ConcurrentHashMap and use Forloop (don’t use Iterator) (2) use HashMap and use method as Synchronized, and ForLoop. (3) use HashMap and use Iterator (don’t use For loop).
-> If multiple threads try to just read the data(not modify) then use ‘HashMap’ and use ForLoop (don’t use Itertor)

====================================================================

HashMap vs ConcurrentHashMap vs Collections.synchronizedMap( HashMap ) :

The difference between HashMap and ConcurrenHashMap we just discussed above.

ConcurrentHashMap contains segments which are nothing but HashMaps (default 16 segments) so that multiple threads can access these multiple segments at a time. There is no lock/blocking for one thread if another thread is accessing. Means Concurrency is achieved here.

Collections.synchronizedMap(HashMap) is a synchronized version of HashMap. Here lock is enabled to the Map, means if one thread is modifying the map another thread can not access it. Means synchronization is achieved here and Map is accessed in blocking manner. This means if multiple threads try to access synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner.

====================================================================

Collections.synchronizedMap( HashMap ) vs HashTable:

Both are synchronized version of collection. Both have synchronized methods inside class. Both are blocking in nature i.e. multiple threads will need to wait for getting the lock on instance before putting/getting anything out of it.

So what is the difference. Well, NO major difference for above said reasons. Performance is also same for both collections.

Only thing which separates them is the fact HashTable is legacy class promoted into collection framework. It got its own extra features like enumerators.

====================================================================

HashMap vs Hashtable detailed:

HashMap Hashtable
Synchronized No Yes
Thread-Safe No Yes
Null Keys and Null values One null key Any null values Not permit null keys and values
Iterator type Fail fast Iterator Fail safe iterator
Performance Fast Slow in comparison
Superclass and Legacy AbstractMap, No Dictionary, Yes

http://javahungry.blogspot.com/2014/03/hashmap-vs-hashtable-difference-with-example-java-interview-questions.html

====================================================================

HashMap, Collections.synchronizedMap, HashTable, ConcurrentHashMap:

HashMap Collections.synchronizedMap HashTable ConcurrentHashMap
What? Map which stores (K, V) pairs. Which doesn’t allow multiple threads to modify the structure of Map. [e.g.: while iterating map, if you try to insert a record, it throws ConcurrentModificationException] Synchronized version of HashMap. [which allows only one thread to access Map a time as the lock is at object level. So lock will be for put, get methods.] Synchronized version of HashMap. [which allows only one thread to access Map a time as the lock is at object level. So lock will be for put, get methods.] This is also synchronized version of HashMap.  which allows multiple threads to modify the records(add/remove) at a time, as the lock is only at HashMap bucket level.
Can Multiple threads can read at a time? Yes Yes Yes Yes
Can Multiple threads can modify size of Map (Add or remove records while iterating) No (gives ConcurrentModificationException) No (gives ConcurrentModificationException) No (gives ConcurrentModificationException) Yes
Syntax HashMap<String, String> hm = new HashMap<> (); HashMap<String, String> hm = Collections.synchronizedMap(new HashMap<> ()); HashTable<String, String> ht = new HashTable<> (); HashMap<String, String> hm = new ConcurrentHashMap<> ();
Null Keys and Null values Can insert one Null key & any no of Null values. Can insert one Null key & any no of Null values. Can’t insert Null keys and Null Values. Can insert one Null key & any no of Null values.
Performance Faster than remaining all. Less compare to HashMap, but same as HashTable. Less compare to HashMap, but same as Collections.synchronizedMap Less compare to HashMap.
Synchronized? No Yes, at Object level Yes, at Object level Yes, at HashMap bucket level.

====================================================================
Default Constructor vs Parameterized Constructor:
-> If you have Default Constructor in your class, when ever you create an object to the class, the default constructor will assign default values to the class objects (global variables). Note that even though you didn’t define default constructor in your class, compiler will creates it.
-> If your have Parameterized Constructor in your class, when ever you create an object to the class by passing parameters defined constructor then those values will be assigned to the global variables.

====================================================================
Flow when record is inserted into HashMap:
HashMap<Price, String> hm = new HashMap<>();
hm.put(new Price(10, “Oranges”),”Fruit Orange”);
Insert Record to HashMap using put-> Hashcode() method’ll be called to get hashcode for key where it stores key, value pair -> Internally it comapares Hashcode generated is already present in Bucket or not -> If already present enters equals(Object obj) method.
====================================================================
Sample Code:

package model;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class Price {

int itemsCount;
String itemName;

Price(int item, String name) {
this.itemsCount = item;
this.itemName = name;
}
Price() {
}

public static void main(String[] args) {

HashMap&amp;amp;lt;Price, String&amp;amp;gt; hm = new HashMap&amp;amp;lt;&amp;amp;gt;();
hm.put(new Price(10, "Oranges"),"Fruit Orange");
hm.put(new Price(20, "Mangos"), "Fruit Mango");
hm.put(new Price(30, "Bananas"), "Fruit Banana");
hm.put(new Price(30, "Bananas"), "Fruit Fruit");
hm.put(new Price(40, "Grapes"), "Fruit Grapes");
System.out.println("size:"+hm.size());

for (Entry&amp;amp;lt;Price, String&amp;amp;gt; entry : hm.entrySet()) {
System.out.println("Key:" + entry.getKey() + " &amp;amp;amp; Value:" + entry.getValue());
}

/*Iterator&amp;amp;lt;Price&amp;amp;gt; keySetIterator = hm.keySet().iterator();
while(keySetIterator.hasNext()){
Object key = keySetIterator.next();
System.out.println("key: " + key+ " value: " + hm.get(key));
}&amp;amp;nbsp;&amp;amp;nbsp; &amp;amp;nbsp;*/
}

//Alt+Shift+S -&amp;amp;gt; Override/Implement methods

@Override
public String toString() {
return this.itemName+this.itemsCount;
//return "ravi";
}

@Override
public int hashCode() {
System.out.println("Hashcode entered..");
// TODO Auto-generated method stub
return new Integer(this.itemsCount).hashCode()+this.itemName.hashCode();
}

@Override
public boolean equals(Object obj) {
if(obj instanceof Price){
System.out.println("equals method..obj is instance of class");
Boolean b = ((Price)obj).itemName.equals(this.itemName) &amp;amp;amp;&amp;amp;amp; (((Price)obj).itemsCount==this.itemsCount);
return (b) ;
}
return false;
//return super.equals(obj);
}
}

Response:
Hashcode entered..
// When First record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
Hashcode entered..
// When Second record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
Hashcode entered..
// When third record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
Hashcode entered..
// When fourth record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
equals method..obj is instance of class
// After fourth record entered as hashcode genreated in fourth reocord is same as hashcode generated in third record, it enteres equals() method
Hashcode entered..
// When fifth record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
size:4  //here you can see only four records in HashMap as fourth record is overriden on third record address.
Key:Oranges10 & Value:Fruit Orange
Key:Bananas30 & Value:Fruit Fruit
Key:Mangos20 & Value:Fruit Mango
Key:Grapes40 & Value:Fruit Grapes

====================================================================
HashMap methods:
put(k,v), get(k), remove(k), size(), clear(), isEmpty(), containsKey(k), containsValue(v), entrySet(), keySet(), putAll(Map)
====================================================================
HashMap memory Allocation:
Default Size of HashMap: 16 and threshold is 0.75% i.e [0.75(16)=12]
So when you insert records in HashMap, when ever it reaches sixe of 12, then HashMap size will be extended to 12+16 = 28.
When ever the records in HashMap reaches [0.75(28)=21], then HashMap size will be extended to 21+16 = 35.
and so on the size wil be extended when ou keep on inserting records to HashMap.
====================================================================
// Do you know that you can not assign null value to int, if you do so, you’ll get NullPointer Exception. You can assign Null value to Integer.
Integer i = null;
int j = i;
System.out.println(“j”+j);  //java.lang.NullPointerException
====================================================================
Loop HashMap records:
/*  HashMap For Loop:
*  HashMap<Integer, String> hm = new HashMap<>();
*  for(Entry<Integer, String> m: hm.entrySet()){ }
*  for(Map.Entry<Integer, String> m:hm.entrySet()){  }
*  for(HashMap.Entry<Integer, String> m: hmap.entrySet()){ }
*  for(Entry m:hm.entrySet()){ } –without type casting
*  Inside for to get key and values -> m.getKey(), m.getValue()
*/

/*  HashMap Itertor and while Loop:
*  HashMap<Integer, String> hm = new HashMap<>();
*  Iterator<Price> keySetIterator = hm.keySet().iterator();
while(keySetIterator.hasNext()){
Object key = keySetIterator.next();
System.out.println(“key: ” + key+ ” value: ” + hm.get(key));
}
*/
====================================================================

HashMap References :
http://www.java2novice.com/java-collections-and-util/hashmap/iterate/
http://www.java2novice.com/java-collections-and-util/hashmap/

Advertisements