Skip to content

Instantly share code, notes, and snippets.

@pawitp
Created October 10, 2011 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pawitp/1274960 to your computer and use it in GitHub Desktop.
Save pawitp/1274960 to your computer and use it in GitHub Desktop.
public class ExpandableArray {
private int[] m_array;
private int m_length;
public ExpandableArray() {
// First initialize to a capacity of 2
m_array = new int[2];
m_length = 0;
}
public int get(int i) {
return m_array[i];
}
public int size() {
return m_length;
}
public void add(int value) {
if (m_length == m_array.length) { // Not enough space
// Create a new array with double the size of the old array
int[] newArray = new int[m_array.length * 2];
// Copy old array into the new one
for (int i = 0; i < m_length; i++) {
newArray[i] = m_array[i];
}
// Replace the old array with a new one
m_array = newArray;
}
m_array[m_length] = value;
m_length++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment