Skip to content

Instantly share code, notes, and snippets.

@jaxbot
Forked from wwsun/MyArrayList.java
Last active January 8, 2017 15:58
Show Gist options
  • Save jaxbot/6ff231fc89c2e7a021ec75f4f553cfdb to your computer and use it in GitHub Desktop.
Save jaxbot/6ff231fc89c2e7a021ec75f4f553cfdb to your computer and use it in GitHub Desktop.
A basic ArrayList implementation(Java)
public class MyArrayList {
private static final int DEFAULT_CAPACITY = 10;
private int theSize;
private int[] theItems;
public MyArrayList() {
clear();
}
public void clear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public void ensureCapacity(int newCapacity) {
if (newCapacity < theSize) return;
int[] old = theItems;
theItems = (int[]) new Object[newCapacity];
for (int i = 0; i < size(); i++) {
theItems[i] = old[i];
}
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
public void trimToSize() {
ensureCapacity(size());
}
public int get(int index) {
if (index < 0 || index >= size()) throw new ArrayIndexOutOfBoundsException();
return theItems[index];
}
public int set(int index, int newVal) {
if (index < 0 || index >= size()) throw new ArrayIndexOutOfBoundsException();
int old = theItems[index];
theItems[index] = newVal;
return old;
}
/**
* add the element to the end of list
*
* @param element is the element you want to add
* @return true if add successfully, otherwise return false
*/
public boolean add(int element) {
add(size(), element);
return true;
}
// remove from specific spot
public int remove(int index) {
int removeItem = theItems[index];
// Shift everything to the left
for (int i = index; i < size() - 1; i++) {
theItems[i] = theItems[i + 1];
}
theSize--;
return removeItem;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment