Skip to content

Instantly share code, notes, and snippets.

@benjic
Created July 3, 2015 02:08
Show Gist options
  • Save benjic/83999382e5340c1ec2fc to your computer and use it in GitHub Desktop.
Save benjic/83999382e5340c1ec2fc to your computer and use it in GitHub Desktop.
public class List {
private static final int INITIAL_ARRAY_SIZE = 6;
private static final char NULL_CHAR = '\u0000';
private char[] mBackingStore;
private int mLength;
public List() {
mBackingStore = new char[INITIAL_ARRAY_SIZE];
mLength = 0;
}
public void removeAtIndex(int i) {
// Assume index is in bounds
// Compute the index of our last stored value
int lastItemIndex = mLength - 1;
// Replace the index to remove with the last item
mBackingStore[i] = mBackingStore[lastItemIndex];
// Set swap to null
mBackingStore[lastItemIndex] = NULL_CHAR;
// reduce the size
mLength--;
}
public void insert(char c) {
// Assume we are not full
mBackingStore[mLength++] = c;
}
public String toString() {
String list = "{ ";
for (int i = 0; i < INITIAL_ARRAY_SIZE; i++) {
char c = mBackingStore[i];
if ( i == mLength ) {
list += "| ";
}
if (mBackingStore[i] != NULL_CHAR) {
list += "[" + c + "] ";
} else {
list += "[ ] ";
}
}
list += "}";
return list;
}
public static void main(String[] args) {
// Lets make a list!
char[] letters = new char[]{'X', 'Y', 'Z'};
List list = new List();
// And fill it with the letters
for ( char letter : letters ) {
list.insert(letter);
}
// Lets look at the list, remove at an index, and look at it again.
System.out.println(list);
list.removeAtIndex(1);
System.out.println(list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment