Skip to content

Instantly share code, notes, and snippets.

@JohnMeyerhoff
Created February 1, 2022 14:29
Show Gist options
  • Save JohnMeyerhoff/6543aa62750504ef22025d14fcdd5c73 to your computer and use it in GitHub Desktop.
Save JohnMeyerhoff/6543aa62750504ef22025d14fcdd5c73 to your computer and use it in GitHub Desktop.
Dynamic Generic Array
import java.util.Iterator;
public class DynamicArray<I> implements Iterable<I> {
class ArrayIterator implements Iterator<I> {
int bookmark = 0;
@Override
public boolean hasNext() {
return bookmark<size()-1;
}
@Override
public I next() {
return get(bookmark++);
}
}
private int size = 0;
private I[] dynamisch = null;
@SuppressWarnings("unchecked")
public DynamicArray() {
dynamisch = (I[]) new Object[2];
}
public int size() {
return this.size;
}
public int capacity() {
return dynamisch.length;
}
public I get(int pos) {
if (pos < 0) {
pos = 0;
}
if (pos > dynamisch.length) {
throw new IllegalArgumentException();
} else {
return this.dynamisch[pos];
}
}
@SuppressWarnings("unchecked")
private void increaseCapacityRshift() {
I[] x = (I[]) new Object[capacity() * 2];
System.arraycopy(dynamisch, 0, x, 1, size);
dynamisch = x;
}
@SuppressWarnings("unchecked")
private void increaseCapacityNoshift() {
I[] x = (I[]) new Object[capacity() * 2];
System.arraycopy(dynamisch, 0, x, 0, size);
dynamisch = x;
}
private void keepCapacityRshift() {
System.arraycopy(dynamisch, 0, dynamisch, 1, size);
}
public void addFirst(I e) {
if (size >= capacity()) {
increaseCapacityRshift();
} else {
keepCapacityRshift();
}
dynamisch[0] = e;
size++;
}
public void addLast(I e) {
if (size >= capacity()) {
increaseCapacityNoshift();
}
dynamisch[size] = e;
size++;
}
public I removeFirst() {
I deleted = dynamisch[0];
for (int i = 0; i < size; i++) {
dynamisch[i] = dynamisch[i + 1];
}
size--;
return deleted;
}
public I removeLast() {
I deleted = dynamisch[size - 1];
dynamisch[--size] = null;
return deleted;
}
@Override
public ArrayIterator iterator() {
return new ArrayIterator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment