后续应该进行压缩
import java.io.Serializable;
import java.util.Arrays;
/**
* 一种节省空间的布尔数组
*/
public class ByteList implements Serializable {
private static final long serialVersionUID = 20220420134730L;
private static final int ATOMICSIZE = 32;
private int size;
private int[] elementData;
public ByteList() {
this.size = 32;
this.elementData = new int[1];
}
public ByteList(int size) {
this.size = (size / ATOMICSIZE) + 1;
this.elementData = new int[size];
}
/**
* 返回 size
* @return
*/
public int size() {
return size * ATOMICSIZE;
}
/**
* 获取 index 位z值
* @param index
* @return
*/
public int get(int index) {
if (index >= size()) {
throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size());
}
int x1 = index / ATOMICSIZE;
int x2 = index % ATOMICSIZE;
return getByteAtIndex(elementData[x1], x2);
}
/**
* 将 index 位置为1
* @param index
*/
public void setOne(int index) {
if (index >= size()) {
grow();
}
int x1 = index / ATOMICSIZE;
int x2 = index % ATOMICSIZE;
elementData[x1] = setOneAtIndex(elementData[x1], x2);
}
/**
* 将 index 位置为0
* @param index
*/
public void setZero(int index) {
if (index >= size()) {
grow();
}
int x1 = index / ATOMICSIZE;
int x2 = index % ATOMICSIZE;
elementData[x1] = setZeroAtIndex(elementData[x1], x2);
}
/**
* 扩容
*/
private void grow() {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
elementData = Arrays.copyOf(elementData, newCapacity);
}
/**
* 获取 int 的 index 位上的二进制值
* @param x
* @param index
* @return
*/
private int getByteAtIndex(int x, int index) {
return (x >> index) & 1;
}
/**
* i位置1: |上i位为1其余为0
*
* @param x
* @param index 0 ~ 31
* @return
*/
private int setOneAtIndex(int x, int index) {
if (index > 31) {
index = 31;
} else if (index < 0) {
index = 0;
}
return x | (1 << index);
}
/**
* i位置0: &上i位为0其余为1
*
* @param x
* @param index 0 ~ 31
* @return
*/
private int setZeroAtIndex(int x, int index) {
if (index > 31) {
index = 31;
} else if (index < 0) {
index = 0;
}
return x & (~(1 << index));
}
}