Created
October 10, 2011 09:50
-
-
Save pawitp/1274960 to your computer and use it in GitHub Desktop.
This file contains 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
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