Showing posts with label HashMap. Show all posts
Showing posts with label HashMap. Show all posts

Thursday 16 April 2015

How to create a read-only collection in java?

Collections is one of the most used feature in Java/J2EE applications . Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java.



 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class ReadOnlyCollections {  
           public static void main(String[] args) {  
                List<String> myList = new ArrayList<>();  
                myList.add("1");  
                myList.add("2");  
                myList.add("3");  
                System.out.println(myList);  
                // Convert to unmodifiable .  
                myList = Collections.unmodifiableList(myList);  
                myList.add("4");  
                System.out.println(myList);  
           }  
 }  
 Output -   
 [1, 2, 3]  
 Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollections.main(ReadOnlyCollections.java:15)  

Wednesday 22 October 2014

Hashmap in Java

If anybody asks me to describe “How HashMap works?“, I simply answer: “On principle of Hashing“. HashMap is a Collection which works on principle of Hashing and it uses key and value pairs to store the information and we can get the value if we pass key to the HashMap. You can also say HashMap is fast as it is not synchronized.

HashMap class comes from java.util package and HashMap class extends AbstractMap and implements Map, Cloneable and Serializable interfaces. HashMap is nothing but Hash table based implementation of Map Interface.



What is Hashing

Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule:

Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.

A little about Entry class

A map by definition is : “An object that maps keys to values”. Very easy.. right?
So, there must be some mechanism in HashMap to store this key value pair. Answer is YES. HashMap has an inner class Entry, which looks like this:

static class Entry implements Map.Entry{
          final K key;
          V value;
          Entry next;
          final int hash;
          ...
}

Surely Entry class has key and value mapping stored as attributes. Key has been marked as final and two more fields are there: next and hash.


put() method in hashmap

We need to pass Key and Value object to put() method in Java HashMap. Once we pass the key and value to in put() method of HashMap, HashMap calls hashCode method on key object and use hashcode into own hashing function to find the bucket location. Bucket is the place where Entry object is stored and hashcode is like an address of that bucket. So what exactly we store in bucket? This is very important to understand. Java stores both Key and Value object as a Map.Entry in bucket. These are stored like LinkedList. But why these are stored as LinkedList. As we know we are using the hashcode to find the bucket location but two unequal objects can have same hashcode. So there are chances of collision. So along with value key is stored.


get() methods in hashmap

We need to pass key to the get method which takes the key as an argument and try to find bucket position using the hashcode. Once it finds the bucket using equals function it gets the value and returns it.

If no match is found, get() method returns null.


Key Notes


  • Data structure to store Entry objects is an array named table of type Entry.
  • A particular index location in array is referred as bucket, because it can hold the first element of a LinkedList of Entry objects.
  • Key object’s hashCode() is required to calculate the index location of Entry object.
  • Key object’s equals() method is used to maintain uniqueness of Keys in map.
  • Value object’s hashCode() and equals() method are not used in HashMap’s get() and put() methods.
  • Hash code for null keys is always zero, and such Entry object is always stored in zero index in Entry[].
  • Order in not maintained in hashmap.


What is the load factor in java HashMap and what happens when size of the HashMap exceeds a given threshold defined by load factor?

Load factor of HashMap is is .75 it will act to re-size the map once it filled 75%, so once size exceeds 75%, then Java HashMap re-size itself by creating a new bucket array of size twice of size defined previously for the HashMap ,then it start putting every old element into that new bucket array. This process is also called rehashing because hash function is used to find the new bucket location.

What are the differences between HashMap and Hashtable?

Lets see what are the differences we can see in HashMap and Hashtable.

1. Synchronization :
Hashtables are synchronized , it means at one point of time only one thread can modify a Hashtable. i.e any thread before performing an update on a hashtable will be acquiring a lock on the object while others will wait for lock to be released.
Hashmap is not synchronized , but we can make it synchronized.

2. Fail-safe:
Iterator of HashMap is fail-safe but the enumerator for the Hashtable is not fail-safe. Lets see what exactly fail-safe is. If an iterator has been created on a collection object and some other thread tries to modify this object , a concurrent modification exception will be thrown. So fail safe is like ability of system to fail but it wont produce some catastrophic results.

3. null values
Hashtable doesn’t allow null but Hashmap allows null values.

Wednesday 25 June 2014

HashSet & HashMap

HashSet:

  • HashSet is implementation of Set Interface and extends AbstractSet class
  • Uses Hash table to store the elements.
  • In Hash set the main thing is that objects which are going to be stored in HashSet must override equals() and hashCode() method so that no duplicate value are stored in our set.
  • Contains unique elements only.
  • HashSet is slower than HashMap.
  • Add method is used to add element in Set. public boolean add(Object o)
  • Example : In the HashSet, there must be no duplicate elements.
       HashSet is a set, e.g. {10,20,30}


HashMap:


  • HashMap is a implementation of Map Interface and extends AbstractMap class, which maps a key to value.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • Basically map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.
  • HashMap is not synchronized, but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our HashMap and one thread is structurally change our map.
  • HashMap is faster than HashSet because unique key is used to access object.
  • Put method is used to add element in map. public Object put(Object Key,Object value)
  • Example : HashMap there must not be duplicate keys, but it may have duplicate values.
        HashMap is a key -> value (key to value) map, e.g. {a -> 10, b -> 20, c -> 20}


Differences between HashSet and HashMap in Java
HashSet internally uses HashMap to store objects. When add(String) method called it calls HahsMap put(key,value) method where key=String object & value=new Object(Dummy). So it maintain no duplicates because keys are nothing but Value Object. Keys which are used to access/store value objects in HashMap should declared as Final because when it is modified Value object can't be located & returns null.

Why add() Method of HashSet return boolean & put() method of HashMap return values?

HashMap put method: Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Return:- the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)



HashSet add method: Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

Returns:- true if this set did not already contain the specified element.