View Javadoc
1   package org.djutils.immutablecollections;
2   
3   import java.util.HashSet;
4   
5   /**
6    * Demonstration code.
7    * @author pknoppers
8    */
9   public final class ImmutableCollectionsDemo
10  {
11      /**
12       * Do not instantiate.
13       */
14      private ImmutableCollectionsDemo()
15      {
16          // Do not instantiate
17      }
18  
19      /**
20       * Demo code.
21       * @param args String[]; not used
22       */
23      public static void main(final String[] args)
24      {
25          HashSet<String> hashSet = new HashSet<>(); // Create a normal HashSet containing Strings
26          hashSet.add("String 1"); // Add a String
27          hashSet.add("String 2"); // Add another String
28          System.out.println("normal hash set contains: " + hashSet);
29          ImmutableHashSet<String> immutableHashSetWithCopy = new ImmutableHashSet<>(hashSet); // Makes a copy
30          ImmutableHashSet<String> immutablehashSetThatWraps = new ImmutableHashSet<>(hashSet, Immutable.WRAP);
31          System.out.println("immutable hash set with copy:  " + immutableHashSetWithCopy); // Contains two Strings
32          System.out.println("immutable hash set that wraps: " + immutablehashSetThatWraps); // Contains two Strings
33          hashSet.add("String 3"); // Modify the original hash set by adding a third String
34          System.out.println("immutable hash set with copy:  " + immutableHashSetWithCopy); // Contains two Strings
35          System.out.println("immutable hash set that wraps: " + immutablehashSetThatWraps); // Contains three Strings
36          ImmutableIterator<String> immutableIterator = immutableHashSetWithCopy.iterator(); // Create an Iterator
37          while (immutableIterator.hasNext()) // Iterate over the immutable hash set
38          {
39              String string = immutableIterator.next();
40              System.out.println("string is " + string);
41              immutableIterator.remove(); // Throws UnsupportedOperationException
42          }
43          // immutableHashSetWithCopy.add("String 4"); // does not compile; there is no add method
44          // immutableHashSetThatWraps.add("String 4"); // does not compile; there is no add method
45          // immutableHashSetWithCopy.remove("String 2"); // does not compile; there is no add method
46          // immutableHashSetThatWraps.remove("String 2"); // does not compile; there is no add method
47      }
48  
49  }