HashSet - making set unmodifiable using Collections.unmodifiableSet






HashSet - making set unmodifiable using Collections.unmodifiableSet




import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class HashSetTest {
   public static void main(String args[]) {
          // creates array with initial capacity of 10.
          Set<String> hashSet = new HashSet<String>();
          hashSet.add("ankit");
          hashSet.add("javaMadeSoEasy");
          // getting unmodifiable HashSet
          Set<String> unmodifiableSet = Collections.unmodifiableSet(hashSet);
         
          /*
          * 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 hashSetUnModifiable.HashSetTest.main(HashSetTest.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


eEdit
Must read for you :