I have been reading the Effective Java book and I have stuck with this code I am unable to understand how this code is generating power set.
Code:
public class PowerSet {
public static final <E> Collection<Set<E>> of(Set<E> s) {
List<E> src = new ArrayList<>(s);
if (src.size() >= 30)
throw new IllegalArgumentException("Set too big " + s);
return new AbstractList<Set<E>>() {
@Override
public int size() {
return 1 << src.size();
}
@Override
public boolean contains(Object o) {
return o instanceof Set && src.containsAll((Set) o);
}
@Override
public Set<E> get(int index) {
Set<E> result = new HashSet<>();
for (int i = 0; index != 0; i++, index >>= 1)
if ((index & 1) == 1)
result.add(src.get(i));
return result;
}
};
}
public static void main(String[] args) {
Collection<Set<String>> result = of(Set.of("a", "b", "c"));
System.out.println(result);
}
}
Output:
[[], [a], [b], [a, b], [c], [a, c], [b, c], [a, b, c]]
Can someone explain how this code is generating powerset of a given set.