/** Implementation of a list of strings using an array. @author Jed Yang, 2018-01-17 */ public class CarlStringList implements List { // instance variables, private private String[] array; private int count; public CarlStringList() { array = new String[10]; count = 0; } /** Live-code. */ public void add(String item) { if (count >= array.length) { resizeArray(); } array[count] = item; count++; } /** Worksheet. */ public String get(int index) { // why should you use count and NOT array.length? if (index < 0 || index >= count) { throw new IndexOutOfBoundsException("index should be between 0 and size - 1"); } return array[index]; } /** Worksheet. */ public void add(int index, String item) { if (count >= array.length) { resizeArray(); } // why is this condition slightly different from the one in get? if (index < 0 || index > count) { throw new IndexOutOfBoundsException("index should be between 0 and size"); } for (int i = count - 1; i >= index; i--) { array[i+1] = array[i]; } array[index] = item; count++; } /** Worksheet. */ private void resizeArray() { // why should you use array.length and NOT count? String[] newArray = new String[array.length*2]; for (int i = 0; i < count; i++) { newArray[i] = array[i]; } array = newArray; } /** Returns the number of elements in the list. @return size of the list */ public int size() { return count; } /** Returns a comma-separated list of the elements. @return string representation */ public String toString() { String s = "["; for (int i = 0; i < count; i++) { if (i > 0) { s += ","; } s += array[i]; } return s + "]"; } /** Demo and test of List methods. */ public static void main(String[] args) { List list1 = new CarlStringList(); list1.add("a"); list1.add("b"); list1.add("c"); list1.add("d"); System.out.println("list should be [a,b,c,d]; actually: " + list1); System.out.println("length should be 4; actually: " + list1.size()); // System.out.println(list1.get(7)); //* try { for (int i = 0; i < 23; i++) { list1.add("lots of stuff"); } } catch (RuntimeException e) { System.err.println("too many things: " + e.getMessage()); } //*/ System.out.println(list1); System.out.println("==============================================="); List list2 = new CarlStringList(); list2.add(0, "a"); list2.add(1, "c"); list2.add(1, "b"); list2.add(3, "d"); System.out.println("list should be [a,b,c,d]; actually: " + list2); System.out.println("length should be 4; actually: " + list2.size()); //*/ } }