View Javadoc
1   package com.exsoinn.util;
2   
3   
4   import java.util.*;
5   
6   /**
7    * A forwarding {@code Set} which cannot be modified once built.
8    *
9    * <strong>WARNING:</strong> A malicious/careless client can still extend this class and override the methods that mutate
10   *   the object, which in this implementation throw {@link UnsupportedOperationException}. Therefore this class
11   *   can at best be considered conditionally thread safe. To provide more robust protection, child classes should be
12   *   declared <code>final</code>.
13   *
14   * Created by QuijadaJ on 5/25/2017.
15   */
16  public class ForwardingImmutableSet<E> implements Set<E> {
17      private final Set<E> list;
18  
19  
20      public ForwardingImmutableSet(Set<? extends E> pSet) {
21          list = new HashSet<>(pSet);
22      }
23  
24      @Override
25      public int size() {
26          return list.size();
27      }
28  
29      @Override
30      public boolean isEmpty() {
31          return list.isEmpty();
32      }
33  
34      @Override
35      public boolean contains(Object o) {
36          return list.contains(o);
37      }
38  
39      @Override
40      public Iterator<E> iterator() {
41          Set<E> newList = new HashSet<>(list);
42          return newList.iterator();
43      }
44  
45      @Override
46      public Object[] toArray() {
47          Set<E> newList = new HashSet<>(list);
48          return newList.toArray();
49      }
50  
51      @Override
52      public <T> T[] toArray(T[] a) {
53          Set<E> newList = new HashSet<>(list);
54          return newList.toArray(a);
55      }
56  
57      @Override
58      public boolean add(E s) {
59          throw new UnsupportedOperationException();
60      }
61  
62      @Override
63      public boolean remove(Object o) {
64          throw new UnsupportedOperationException();
65      }
66  
67      @Override
68      public boolean containsAll(Collection<?> c) {
69          return list.containsAll(c);
70      }
71  
72      @Override
73      public boolean addAll(Collection<? extends E> c) {
74          throw new UnsupportedOperationException();
75      }
76  
77      @Override
78      public boolean retainAll(Collection<?> c) {
79          throw new UnsupportedOperationException();
80      }
81  
82      @Override
83      public boolean removeAll(Collection<?> c) {
84          throw new UnsupportedOperationException();
85      }
86  
87      @Override
88      public void clear() {
89          throw new UnsupportedOperationException();
90      }
91  
92      @Override
93      public String toString() {
94          return list.toString();
95      }
96  }