Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

import java.util.ArrayList; public class ArrayListUtil { /** Removes adjacent du

ID: 3915300 • Letter: I

Question

import java.util.ArrayList; public class ArrayListUtil { /** Removes adjacent duplicates from an array list of strings. @param word an array list of strings */ public static void removeAdjacentDuplicates(ArrayList words) { . . . } }

import java.util.Arrays;
import java.util.ArrayList;

public class Tester
{
   public static void main(String[] args)
   {
      ArrayList<String> words1 = new ArrayList<String>(Arrays.asList(
            "Typing a a word twice is is a common mistake".split(" ")));
      ArrayListUtil.removeAdjacentDuplicates(words1);
      System.out.println(words1);
      System.out.println("Expected: [Typing, a, word, twice, is, a, common, mistake]");
      ArrayList<String> words2 = new ArrayList<String>(Arrays.asList(
            "Typing a word three times is is is not so common".split(" ")));
      ArrayListUtil.removeAdjacentDuplicates(words2);
      System.out.println(words2);
      System.out.println("Expected: [Typing, a, word, three, times, is, not, so, common]");
   }
}

Explanation / Answer

ArrayListUtil.java:

import java.util.ArrayList;

public class ArrayListUtil
{
public static void removeAdjacentDuplicates(ArrayList input)
{
// Iterate the list from end
for(int i = input.size()-1; i > 0; i--)
{
// Compare current value to previous
if(input.get(i-1).equals(input.get(i)))
{
input.remove(i); //if they are same remove the current value.
}
}
}
}

Main.java:

import java.util.Arrays;

import java.util.ArrayList;

public class Main

{

public static void main(String[] args) {

ArrayList<String> words1 = new ArrayList<String>(Arrays.asList(

"Typing a a word twice is is a common mistake".split(" ")));

ArrayListUtil.removeAdjacentDuplicates(words1);

System.out.println(words1);

System.out.println("Expected: [Typing, a, word, twice, is, a, common, mistake]");

ArrayList<String> words2 = new ArrayList<String>(Arrays.asList(

"Typing a word three times is is is not so common".split(" ")));

ArrayListUtil.removeAdjacentDuplicates(words2);

System.out.println(words2);

System.out.println("Expected: [Typing, a, word, three, times, is, not, so, common]");

}

}

Output:

[Typing, a, word, twice, is, a, common, mistake]                                                                               

Expected: [Typing, a, word, twice, is, a, common, mistake]                                                                     

[Typing, a, word, three, times, is, not, so, common]                                                                           

Expected: [Typing, a, word, three, times, is, not, so, common]