1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.opensaml.xml.util;
18
19 import java.io.Serializable;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.Set;
25
26 import net.jcip.annotations.NotThreadSafe;
27
28
29
30
31
32
33 @NotThreadSafe
34 public class LazySet<ElementType> implements Set<ElementType>, Serializable {
35
36
37 private static final long serialVersionUID = -1596445680460115174L;
38
39
40 private Set<ElementType> delegate = Collections.emptySet();
41
42
43 public boolean add(ElementType element) {
44 if (delegate.isEmpty()) {
45 delegate = Collections.singleton(element);
46 return true;
47 } else {
48 delegate = createImplementation();
49 return delegate.add(element);
50 }
51 }
52
53
54 public boolean addAll(Collection<? extends ElementType> collection) {
55 if(collection == null || collection.isEmpty()){
56 return false;
57 }
58
59 delegate = createImplementation();
60 return delegate.addAll(collection);
61 }
62
63
64 public void clear() {
65 delegate = Collections.emptySet();
66 }
67
68
69 public boolean contains(Object element) {
70 return delegate.contains(element);
71 }
72
73
74 public boolean containsAll(Collection<?> collection) {
75 return delegate.containsAll(collection);
76 }
77
78
79 public boolean isEmpty() {
80 return delegate.isEmpty();
81 }
82
83
84 public Iterator<ElementType> iterator() {
85 return delegate.iterator();
86 }
87
88
89 public boolean remove(Object element) {
90 delegate = createImplementation();
91 return delegate.remove(element);
92 }
93
94
95 public boolean removeAll(Collection<?> collection) {
96 if(collection == null || collection.isEmpty()){
97 return false;
98 }
99
100 delegate = createImplementation();
101 return delegate.removeAll(collection);
102 }
103
104
105 public boolean retainAll(Collection<?> collection) {
106 delegate = createImplementation();
107 return delegate.retainAll(collection);
108 }
109
110
111 public int size() {
112 return delegate.size();
113 }
114
115
116 public Object[] toArray() {
117 return delegate.toArray();
118 }
119
120
121 public <T> T[] toArray(T[] type) {
122 return delegate.toArray(type);
123 }
124
125
126
127
128
129
130 private Set<ElementType> createImplementation() {
131 if (delegate instanceof HashSet) {
132 return delegate;
133 }
134
135 return new HashSet<ElementType>(delegate);
136 }
137 }