曹耘豪的博客

Java:跟着EnumSet学位操作

  1. 介绍
  2. 批量初始化addRange
  3. 补充complement(反转)
  4. 大小size
  5. 是否为空isEmpty
  6. 包含contains
  7. 添加add
  8. 移除remove
  9. 包含所有containsAll
  10. 添加所有addAll
  11. 移除所有removeAll
  12. 保留所有retainAll
  13. 清除所有clear
  14. equals

介绍

EnumSet方便我们去处理enum类型的集合类型,该工具类实现Set接口,内部则使用位运算,在空间复杂度和时间复杂度上都有极大的优势,可以通过该类学习Java的位运算

批量初始化addRange

1
2
3
void addRange(E from, E to) {
elements = (-1L >>> (from.ordinal() - to.ordinal() - 1)) << from.ordinal();
}

补充complement(反转)

1
2
3
4
5
6
void complement() {
if (universe.length != 0) {
elements = ~elements;
elements &= -1L >>> -universe.length; // Mask unused bits
}
}

大小size

1
2
3
public int size() {
return Long.bitCount(elements);
}

是否为空isEmpty

1
2
3
public boolean isEmpty() {
return elements == 0;
}

包含contains

1
2
3
public boolean contains(Object e) {
return (elements & (1L << e.ordinal())) != 0;
}

添加add

1
2
3
4
5
public boolean add(E e) {
long oldElements = elements;
elements |= (1L << ((Enum<?>)e).ordinal());
return elements != oldElements;
}

移除remove

1
2
3
4
5
public boolean remove(Object e) {
long oldElements = elements;
elements &= ~(1L << ((Enum<?>)e).ordinal());
return elements != oldElements;
}

包含所有containsAll

1
2
3
4
5
6
7
public boolean containsAll(Collection<?> c) {
RegularEnumSet<?> es = (RegularEnumSet<?>)c;
if (es.elementType != elementType)
return es.isEmpty();

return (es.elements & ~elements) == 0;
}

添加所有addAll

1
2
3
4
5
6
7
8
public boolean addAll(Collection<? extends E> c) {
RegularEnumSet<?> es = (RegularEnumSet<?>)c;

long oldElements = elements;
elements |= es.elements;

return elements != oldElements;
}

移除所有removeAll

1
2
3
4
5
6
7
public boolean removeAll(Collection<?> c) {
RegularEnumSet<?> es = (RegularEnumSet<?>)c;

long oldElements = elements;
elements &= ~es.elements;
return elements != oldElements;
}

保留所有retainAll

1
2
3
4
5
6
7
public boolean retainAll(Collection<?> c) {
RegularEnumSet<?> es = (RegularEnumSet<?>)c;

long oldElements = elements;
elements &= es.elements;
return elements != oldElements;
}

清除所有clear

1
2
3
public void clear() {
elements = 0;
}

equals

1
2
3
4
5
6
public boolean equals(Object o) {
RegularEnumSet<?> es = (RegularEnumSet<?>)o;
if (es.elementType != elementType)
return elements == 0 && es.elements == 0;
return es.elements == elements;
}
   /