This exercise demonstrates common issues when adding to or removing from an ArrayList
.
The Java files below include skeleton code for each method and a JUnit 5 tester for each method. See Running JUnit 5 tests.
ArrayListPractice.java
ArrayListPracticeTest.java
removeWord
method
/**
* Removes all occurrences of wordToRemove from words
* @param words the word to remove
* @param wordToRemove the list from which to remove word
*/
public static void removeWord(ArrayList<String> words, String wordToRemove)
removeWord
examples
ArrayList<String> words = new ArrayList<String>(Arrays.asList(
"the", "happy", "cat", "ate", "the", "unhappy", "rat"));
ArrayListPractice.removeWord(words, "the");
System.out.println(words);
// prints: [happy, cat, ate, unhappy, rat]
words = new ArrayList<String>(Arrays.asList(
"a", "blue", "blue", "blue", "bird","ate", "a",
"blue", "blue", "worm", "too", "much", "blue"));
ArrayListPractice.removeWord(words, "blue");
System.out.println(words);
// prints: [a, bird, ate, a, worm, too, much]
duplicateMatching
method
/**
* Duplicates each element in list that matches elem. Each duplicate
* element is adjacent to the original element.
* @param list the list from which to duplicate elements
* @param elem the element to duplicate
*/
public static void duplicateMatching(ArrayList<Integer> list, Integer elem)
duplicateMatching
example
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(
5, 7, 5, 7, 7, 9, 5, 7));
ArrayListPractice.duplicateMatching(list, 7);
System.out.println(list);
// prints: [5, 7, 7, 5, 7, 7, 7, 7, 9, 5, 7, 7]
removeAdjacentDuplicates
method
/**
* Removes all adjacent duplicate elements from list.
* @param list the list from which to remove elements
*/
public static void removeAdjacentDuplicates(ArrayList<Integer> list)
removeAdjacentDuplicates
examples
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(
5, 7, 7, 5, 3, 7, 7, 7, 8, 7, 7, 7, 7));
ArrayListPractice.removeAdjacentDuplicates(list);
System.out.println(list);
// prints: [5, 7, 5, 3, 7, 8, 7]
list = new ArrayList<Integer>(); // empty list
ArrayListPractice.removeAdjacentDuplicates(list);
System.out.println(list);
// prints: []
list = new ArrayList<Integer>();
list.add(5);
ArrayListPractice.removeAdjacentDuplicates(list);
System.out.println(list);
// prints: [5]
Solution & comments
See the ArrayList practice solution or review it with AP CS Tutor Brandon Horn.