/* An object of class DynamicArrayOfInt acts like an array with unlimited size. The method put(position,value) is used to store the value at the specifed position in the array. There is no pre-set limit on how large position can be, although for very large values there would be problems with having enough computer memory. The function get(position) is used to retrieve the value stored in the specified position. If no value has ever been put at that position, then the value is zero. */ public class DynamicArrayOfInt { private int[] data; // An array to hold the data. The actual size // of the array will increase as necessary. public DynamicArrayOfInt() { // Constructor. Create a new DynamicArrayOfInt object. // Initally, the data array only has size 1, but it will // grow as necessary. data = new int[1]; } public int get(int position) { // Get the value from the specified position in the array. // Since all array positions are initially zero, when the // specified position lies outside the actual physical size // of the data array, a value of 0 is returned. However, the // array does NOT grow to include the specified position. if (position >= data.length) return 0; else return data[position]; } public void put(int position, int value) { // Store the value in the specified position in the array. // The data array will increase in size to include this // position, if necessary. if (position >= data.length) { // The specified position is outside the actual size of // the data array. Double the size, or if that still does // not include the specified position, set the new size // to 2*position. A new, larger array is created and // all the data from the old array is copied into it. // Then the instance variable, data, is set to refer // to the newly created array. int newSize = 2 * data.length; if (position >= newSize) newSize = 2 * position; int[] newData = new int[newSize]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; // The following line is here for demonstration purposes only. System.out.println("Size of dynamic array increased to " + newSize); } data[position] = value; } } // end class DynamicArrayOfInt