Skip to content

Instantly share code, notes, and snippets.

@theoperatore
Last active December 14, 2015 10:39
Show Gist options
  • Save theoperatore/5073983 to your computer and use it in GitHub Desktop.
Save theoperatore/5073983 to your computer and use it in GitHub Desktop.
Brute force method -- Should be Linear Time, dependent on the size of the array
public class BruteArray<E> implements BruteArrayInterface<E>{
private E[] items;
private int numItems;
private static final int INIT_SIZE = 5;
@SuppressWarnings("unchecked")
public BruteArray() {
items = (E[])(new Object[INIT_SIZE]);
numItems = 0;
}
@SuppressWarnings("unchecked")
public void add(E item) {
try {
//try to add the item to the end
items[numItems] = item;
numItems++;
} catch(IndexOutOfBoundsException e) {
//iff the array is full expand it.
E[] brute = (E[])(new Object[items.length * 2]);
//loop through the old array, copying over all elements to new
//bigger array
for (int i = 0; i < items.length; i++) {
brute[i] = items[i];
}
//add the newest item
brute[numItems] = item;
//use the new array as the main array
items = brute;
//increment index
numItems++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment