这是一个作为数组的小型 Set 实现:
它很容易满足您的需求:)
来源: https ://highlyscalable.wordpress.com/2011/12/29/ultimate-sets-and-maps-for-java-p1/
public class ArraySet {
private int[] array;
private int size = 0;
public ArraySet(int capacity) {
array = new int[capacity];
Arrays.fill(array, -1);
}
public boolean add(int key) {
int index = Arrays.binarySearch(array, 0, size, key);
if (index < 0) {
int insertIndex = -index-1;
if(size < array.length - 1) {
if(insertIndex < size) {
System.arraycopy(array, insertIndex, array, insertIndex + 1, size - insertIndex);
}
array[insertIndex] = key;
} else {
int[] newArray = new int[array.length + 1];
System.arraycopy(array, 0, newArray, 0, insertIndex);
System.arraycopy(array, insertIndex, newArray, insertIndex + 1, array.length - insertIndex);
newArray[insertIndex] = key;
array = newArray;
}
size++;
return true;
}
return false;
}
public int get(int position) {
return array[position];
}
public int size() {
return size;
}
public boolean contains(int key) {
return Arrays.binarySearch(array, key) >= 0;
}
}