Change to ByIdArray

This commit is contained in:
fullwall 2012-01-22 16:04:10 +08:00
parent c221abc75d
commit f5f5b7b583

View File

@ -9,6 +9,7 @@ public class ByIdArray<T> implements Iterable<T> {
private int size; private int size;
private int modCount; private int modCount;
private int highest; private int highest;
private int lowest;
public ByIdArray() { public ByIdArray() {
this(50); this(50);
@ -21,7 +22,7 @@ public class ByIdArray<T> implements Iterable<T> {
} }
public void clear() { public void clear() {
modCount = highest = size = 0; modCount = highest = size = lowest = 0;
elementData = new Object[50]; elementData = new Object[50];
} }
@ -36,12 +37,19 @@ public class ByIdArray<T> implements Iterable<T> {
} }
private void fastRemove(int index) { private void fastRemove(int index) {
if (index == lowest)
recalcLowest();
if (index == highest) if (index == highest)
recalcHighest(); recalcHighest();
elementData[index] = null; elementData[index] = null;
--size; --size;
} }
private void recalcLowest() {
while (elementData.length > lowest && elementData[lowest++] == null)
;
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T get(int index) { public T get(int index) {
if (index > elementData.length) if (index > elementData.length)
@ -64,7 +72,7 @@ public class ByIdArray<T> implements Iterable<T> {
@Override @Override
public Iterator<T> iterator() { public Iterator<T> iterator() {
return new Iterator<T>() { return new Iterator<T>() {
private int idx = 0; private int idx = lowest;
@Override @Override
public boolean hasNext() { public boolean hasNext() {
@ -96,6 +104,8 @@ public class ByIdArray<T> implements Iterable<T> {
++modCount; ++modCount;
if (index > highest) if (index > highest)
highest = index; highest = index;
if (index < lowest)
lowest = index;
ensureCapacity(index + 1); ensureCapacity(index + 1);
@ -110,6 +120,8 @@ public class ByIdArray<T> implements Iterable<T> {
public T remove(int index) { public T remove(int index) {
++modCount; ++modCount;
if (index == lowest)
recalcLowest();
if (index == highest) if (index == highest)
recalcHighest(); recalcHighest();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")