public class ArrayOperations { public static void main(String[] args) { String[] wordList = getWords(); System.out.println("Array Length: " + wordList.length); displayList(wordList); // Remove the word at spot (index) 3 in the list (version 'A') // removeWordVersionA(wordList, 3); // displayList(wordList); // Remove the word at spot (index) 3 in the list (version 'B') // wordList = removeWordVersionB(wordList, 3); // displayList(wordList); // Remove first occurrence of the word "bear" in the list // removeWord(wordList, "bear"); // displayList(wordList); // Add "fish" to the list // wordList = addWordAtEnd(wordList, "fish"); // displayList(wordList); // Insert "fish" to a spot within the list // wordList = addWordInMiddle(wordList, "fish", 2); // displayList(wordList); // Move word at spot #2 ("elephant") to new spot #4 (before "giraffe") // moveWord(wordList, 2, 4); // displayList(wordList); } public static void displayList(String[] list) { // Display contents of array using a 'for-each' ("enhanced for") loop System.out.print("\nLIST OF ARRAY ELEMENTS:\n"); for (String i : list) System.out.println(i); } public static String[] getWords() { String[] newList = new String[] {"cat", "dog", "elephant", "bear", "zebra", "giraffe", "bear", "dog"}; return newList; } public static void removeWordVersionA(String[] list, int indexToRemove) { for (int i = indexToRemove; i < list.length - 1; i++) list[i] = list[i + 1]; list[list.length - 1] = null; } public static String[] removeWordVersionB(String[] list, int indexToRemove) { String[] newList = new String[list.length - 1]; int spot = 0; for (int i = 0; i < list.length; i++) if (i != indexToRemove) newList[spot++] = list[i]; return newList; } public static void removeWord(String[] list, String wordToRemove) { for (int i = 0; i < list.length; i++) { if (list[i] != null && list[i].equals(wordToRemove)) // Example of short-circuiting { for (int j = i; j < list.length - 1; j++) { list[j] = list[j + 1]; } list[list.length - 1] = null; break; // To remove ALL occurrences of the word, comment out this line } } } public static String[] addWordAtEnd(String[] list, String wordToAdd) { String[] newList = new String[list.length + 1]; for (int i = 0; i < list.length; i++) newList[i] = list[i]; newList[newList.length - 1] = wordToAdd; return newList; } public static String[] addWordInMiddle(String[] list, String wordToAdd, int indexToAdd) { String[] newList = new String[list.length + 1]; for (int i = 0; i < indexToAdd; i++) newList[i] = list[i]; newList[indexToAdd] = wordToAdd; for (int i = indexToAdd; i < list.length; i++) newList[i + 1] = list[i]; return newList; } public static void moveWord(String[] list, int spot1, int spot2) { String hold = list[spot1]; for (int i = spot1; i < spot2; i++) list[i] = list[i + 1]; list[spot2] = hold; } }