Thursday 5 November 2015

Collections class: Read-Only Collections


Read-Only Collections: When working with collection, there are times when you need or at least prefer an unmodifiable access to your collection instance. This may be because you are finished adding and removing elements from the collection but you still want to use it or you need to pass your collection to some method which you don’t necessarily know or you know the method but you don’t want them to change anything. To provide this capability, the Collections class provides six factory methods, one for each of Collection, List, Map, Set, SortedMap, and SortedSet.
         
  •       Collection unmodifiableCollection(Collection collection)
  •       List unmodifiableList(List list)
  •           Map unmodifiableMap(Map map)
  •       Set unmodifiableSet(Set set) 
  •             SortedMap unmodifiableSortedMap(SortedMap map)
  •       SortedSet unmodifiableSortedSet(SortedSet set)



Once you've filled the collection, replace the original reference with the read-only reference.If you don't replace the original reference, then the collection is not read-only, as you can still use the original reference to modify the collection. The following program demonstrates the proper way to make a collection read-only. In addition, it shows what happens when you try to modify a read-only collection.

 import java.util.Collections;  
 import java.util.HashSet;  
 import java.util.Set;  
 public class ReadOnlyCollectionExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Set set = new HashSet();  
           set.add("Cat");  
           set.add("Dog");  
           set.add("Frog");  
           set.add("Elephant");  
           set = Collections.unmodifiableSet(set);  
           set.add("Lion");  
      }  
 }  

Output:-

Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollectionExample.main(ReadOnlyCollectionExample.java:22) 


When the program is run and the last add() operation is attempted on the read-only set, an UnsupportedOperationException is thrown.


Enjoy Reading



No comments:

Post a Comment