Skip to content

Commit

Permalink
Fixed inner set of KeySet not reflecting the set itself
Browse files Browse the repository at this point in the history
  • Loading branch information
OmerBenGera committed Jun 3, 2022
1 parent ee6fca5 commit de81abe
Showing 1 changed file with 98 additions and 1 deletion.
Expand Up @@ -8,6 +8,7 @@
import javax.annotation.Nullable;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
Expand All @@ -18,6 +19,8 @@ public final class KeySetImpl extends AbstractSet<Key> implements KeySet {

private final Set<String> set;

private Set<Key> innerReflectedSet;

public static KeySetImpl create(Supplier<Set<String>> setCreator, Collection<Key> keys) {
return new KeySetImpl(setCreator, keys.stream().map(Object::toString).collect(Collectors.toSet()));
}
Expand Down Expand Up @@ -86,7 +89,101 @@ else if (set.contains(original.getGlobalKey()))

@Override
public Set<Key> asSet() {
return this.set.stream().map(KeyImpl::of).collect(Collectors.toSet());
return Collections.unmodifiableSet(innerReflectedSet == null ? (innerReflectedSet = new InnerReflectedSet()) : innerReflectedSet);
}

private final class InnerReflectedSet implements Set<Key> {

@Override
public int size() {
return KeySetImpl.this.set.size();
}

@Override
public boolean isEmpty() {
return KeySetImpl.this.set.isEmpty();
}

@Override
public boolean contains(Object o) {
return KeySetImpl.this.set.contains(o);
}

@NotNull
@Override
public Iterator<Key> iterator() {
return new SetIterator();
}

@Override
public Object @NotNull [] toArray() {
return KeySetImpl.this.set.toArray();
}

@Override
public <T> T @NotNull [] toArray(T @NotNull [] a) {
return KeySetImpl.this.set.toArray(a);
}

@Override
public boolean add(Key key) {
// No implementation
return false;
}

@Override
public boolean remove(Object o) {
// No implementation
return false;
}

@Override
public boolean containsAll(@NotNull Collection<?> c) {
return KeySetImpl.this.set.containsAll(c);
}

@Override
public boolean addAll(@NotNull Collection<? extends Key> c) {
// No implementation
return false;
}

@Override
public boolean retainAll(@NotNull Collection<?> c) {
// No implementation
return false;
}

@Override
public boolean removeAll(@NotNull Collection<?> c) {
// No implementation
return false;
}

@Override
public void clear() {
// No implementation
}
}

private final class SetIterator implements Iterator<Key> {

final Iterator<String> innerSetIterator = KeySetImpl.this.set.iterator();

@Override
public boolean hasNext() {
return innerSetIterator.hasNext();
}

@Override
public Key next() {
return KeyImpl.of(innerSetIterator.next());
}

@Override
public void remove() {
innerSetIterator.remove();
}
}

}

0 comments on commit de81abe

Please sign in to comment.