LinkedHashSet - making set unmodifiable using Collections.unmodifiableSet



LinkedHashSet  - making set unmodifiable using Collections.unmodifiableSet




import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class LinkedHashSetUnmodifiableExample {
   public static void main(String args[]) {
          // creates array with initial capacity of 10.
          Set<String> linkedLinkedHashSet = new LinkedHashSet<String>();
          linkedLinkedHashSet.add("ankit");
          linkedLinkedHashSet.add("javaMadeSoEasy");
          // getting unmodifiable LinkedHashSet
          Set<String> unmodifiableSet = Collections.unmodifiableSet(linkedLinkedHashSet);
         
          /*
          * Now any attempt to modify list will throw java.lang.UnsupportedOperationException
          */
          unmodifiableSet.add("mittal");
   }
}
/*OUTPUT
Exception in thread "main" java.lang.UnsupportedOperationException
   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
   at LinkedHashSetUnmodifiableExample.main(LinkedHashSetUnmodifiableExample.java:24)
*/




RELATED LINKS>


HashSet - fail-safe or fail-fast iteration using iterator, Enumeration and enhanced for loop program


HashSet - making set unmodifiable using Collections.unmodifiableSet


CopyOnWriteArraySet - add, contains, remove, size methods program


No comments:

Post a Comment