Question: Write a method that removes the duplicate elements from an array list of integers using the following header:
public static void removeDuplicate(ArrayList
Write a test program that prompts the user to enter 10 integers to a list and displays the distinct integers in their input order separated by exactly one space.
Warning!
Please import selected Java packages or use import java.util.*;. Do not copy my code as per copyright and plagiarism regulations. This Java code is provided as it is for demonstration purposes.Solution 1:
import java.util.Scanner;
import java.util.ArrayList;
public class RemoveDuplicate {
public static void main(String[] args) {
System.out.print("Enter ten integers: ");
ArrayList<Integer> list = new ArrayList<>();
Scanner input = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
list.add(input.nextInt());
}
removeDuplicate(list);
System.out.print("The distinct integers are ");
for (int i = 0; i < list.size(); i++)
System.out.print(list.get(i) + " ");
}
public static void removeDuplicate(ArrayList<Integer> list) {
ArrayList<Integer> temp = new ArrayList<>();
for (int i = 0; i < list.size(); i++)
if (!temp.contains(list.get(i)))
temp.add(list.get(i));
list.clear();
for (int i = 0; i < temp.size(); i++)
list.add(temp.get(i));
}
}
Solution 2:
import java.util.Scanner;
import java.util.ArrayList;
public class RemoveDuplicate {
/** Main method */
public static void main(String[] args) {
// Create a scanner
Scanner input = new Scanner(System.in);
// Create an ArrayList
ArrayList<Integer> list = new ArrayList<Integer>();
// Prompt ther user to enter 10 integers
System.out.print("Enter 10 integers: ");
for (int i = 0; i < 10; i++) {
list.add(input.nextInt());
}
// Invoke removeDuplicate method
removeDuplicate(list);
// Display the distinct integers
System.out.print("The distinct integers are ");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
}
public static void removeDuplicate(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i) == list.get(j))
list.remove(j);
}
}
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i) == list.get(j))
list.remove(j);
}
}
}
}
Output:
Sample Run 1
Enter ten integers: 34 5 3 5 6 4 33 2 2 4
The distinct integers are 34 5 3 6 4 33 2
Sample Run 2
Enter ten integers: 3 3 4 4 1 1 2 2 5 5
The distinct integers are 3 4 1 2 5
Sample Run 3
Enter ten integers: 1 2 2 3 4 5 6 7 8 8
The distinct integers are 1 2 3 4 5 6 7 8
Sample Run 4
Enter ten integers: 5 4 3 2 65 4 4 5 1 5
The distinct integers are 5 4 3 2 65 1