Skip to content

Instantly share code, notes, and snippets.

@Darkyenus
Created December 15, 2020 21:21
Show Gist options
  • Save Darkyenus/60dcc83fd1061f3cead2e8ce8dd2cc29 to your computer and use it in GitHub Desktop.
Save Darkyenus/60dcc83fd1061f3cead2e8ce8dd2cc29 to your computer and use it in GitHub Desktop.
A mix between Pool and an Array. Public domain or MIT0 license.
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Pool;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* A dynamically sized array, whose elements are all pooled.
*/
public final class PooledArray<T> {
private final Class<T> elementType;
private T[] items;
private int size;
public PooledArray(Class<T> elementType) {
this.elementType = elementType;
//noinspection unchecked
items = (T[]) Array.newInstance(elementType, 16);
}
public void ensureCapacity(int extraElements) {
if (size + extraElements <= items.length) {
return;
}
int newCapacity = MathUtils.nextPowerOfTwo(size + extraElements);
assert newCapacity > items.length;
items = Arrays.copyOf(items, newCapacity);
}
public T add() {
ensureCapacity(1);
T item = items[size];
if (item == null) {
try {
items[size] = item = elementType.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Failed to instantiate new element", e);
}
} else if (item instanceof Pool.Poolable) {
((Pool.Poolable) item).reset();
}
size++;
return item;
}
public T get(int index) {
assert index >= 0 && index < size;
return items[index];
}
public int size() {
return size;
}
public void clear() {
size = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment