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>