Last active
December 30, 2015 05:08
-
-
Save maxcountryman/7780313 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
class DynamicArray<E> { | |
private transient Object[] elementData; | |
private int size; | |
private int modCount = 0; | |
private int a = 2; | |
public DynamicArray(int initialCapacity) { | |
if (initialCapacity < 0) | |
throw new IllegalArgumentException("Illegal Capacity: " + | |
initialCapacity); | |
this.elementData = new Object[initialCapacity]; | |
} | |
public DynamicArray() { | |
this(10); | |
} | |
private void ensureCapacity(int minCapacity) { | |
modCount++; | |
if (minCapacity - elementData.length > 0) | |
grow(minCapacity); | |
} | |
private void grow(int minCapacity) { | |
int oldCapacity = elementData.length; | |
int newCapacity = oldCapacity * a; | |
elementData = Arrays.copyOf(elementData, newCapacity); | |
} | |
public int size() { | |
return size; | |
} | |
public boolean isEmpty() { | |
return size == 0; | |
} | |
@SuppressWarnings("unchecked") | |
E elementData(int index) { | |
return (E) elementData[index]; | |
} | |
public E get(int index) { | |
rangeCheck(index); | |
return elementData(index); | |
} | |
public E set(int index, E element) { | |
rangeCheck(index); | |
E oldValue = elementData(index); | |
elementData[index] = element; | |
return oldValue; | |
} | |
public boolean add(E element) { | |
ensureCapacity(size + 1); | |
elementData[size++] = element; | |
return true; | |
} | |
private void rangeCheck(int index) { | |
if (index >= size) | |
throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); | |
} | |
private String outOfBoundsMsg(int index) { | |
return "Index: "+index+", Size: "+size; | |
} | |
} | |
class DynamicArrayTest { | |
public static void main(String[] args) { | |
DynamicArray<String> array = new DynamicArray<String>(); | |
array.add("foo"); | |
array.add("bar"); | |
array.add("baz"); | |
assert array.size() == 3; | |
assert array.get(0) == "foo"; | |
assert array.get(1) == "bar"; | |
assert array.get(2) == "baz"; | |
String[] foo = {"one", | |
"two", | |
"three", | |
"four", | |
"five", | |
"six", | |
"seven", | |
"eight"}; | |
// add another eight elements to the array, extending the size of the | |
// array | |
for (String item : foo) { | |
array.add(item); | |
} | |
assert array.size() == 11; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment