In: Computer Science
Write a Java method that removes any duplicate elements from an ArrayList of integers. The method has the following header(signature):
public static void removeDuplicate(ArrayList<Integer> list)
Write a test program (with main method) that prompts the user to enter 10 integers to a list and displays the distinct integers separated by exactly one space. Here is what the input and output should look like:
Enter ten integers: 28 4 2 4 9 8 27 1 1 9
The distinct integers are 28 4 2 9 8 27 1
// RemoveDuplicates.java
import java.util.Scanner;
import java.util.ArrayList;
public class RemoveDuplicates
{
public static void removeDuplicate(ArrayList<Integer>
integerList)
{
ArrayList<Integer> temporaryList = new ArrayList<>();
for (int i = 0; i < integerList.size(); i++)
{
// check for duplicates
if (!temporaryList.contains(integerList.get(i)))
{
// add to temporary list
temporaryList.add(integerList.get(i));
}
}
// clear the integer list
integerList.clear();
// add the temp list to ineter list
integerList.addAll(temporaryList);
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int size = 10;
int number;
ArrayList<Integer> integerList = new ArrayList<>();
System.out.print("Enter ten integers: ");
for (int i = 0; i < size; i++)
{
number = scan.nextInt();
integerList.add(number);
}
// calling the method
removeDuplicate(integerList);
System.out.println("The distinct integers are " +
integerList);
}
}
/*
output:
Enter ten integers: 28 4 2 4 9 8 27 1 1 9
The distinct integers are [28, 4, 2, 9, 8, 27, 1]
*/