Showing posts with label Hashmap. Show all posts
Showing posts with label Hashmap. Show all posts

Monday, 1 September 2014

How to create a readonly 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)  

Monday, 28 July 2014

Why hashmap key must be immutable?

HashMap is a data-structure where data is organized as key and values pairs. i.e. for every value there must be a  key to be produced to be stored into the hashmap.

Keys are normally generated using hashcode() method.

Key’s hash code is used primarily in conjunction to its equals() method, for putting a key in map and then searching it back from map. So if hash code of key object changes after we have put a key-value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak. To avoid this, map keys should be immutable.

I have already posted how to make objects immutable in one of my previous posts. 

Sunday, 27 July 2014

ConcurrentAcessModification Exception Java

 

ConcurrentAcessModification Exception Java


This exception does not normally have anything to do with synchronization - it is normally thrown if a Collection is modified while an Iterator is iterating through it. AddAll methods may use an iterator - and its worth noting that the posh foreach loop iterates over instances of Iterator too.

Example - 

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Test{
   
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(1,"1");
        map.put(2,"2");
        map.put(3,"3");
        map.put(4,"4");
        map.put(5,"5");
        map.put(6,"6");
        Set keyset = map.keySet();
        Iterator iterator = keyset.iterator();
        while(iterator.hasNext()){
          System.out.println(map.get((Integer)iterator.next()));

          // Here you will get java.lang.ConcurrentAccessModification Exception.
            map.put(6,"6");
            map.put(7,"7");
          
        }
    }

}