程序的功能是刪除Arraylist<Character>
中的重複項。在靜態方法removeDuplicate()
中,我首先將重複的位置分配到LinkedList
,然後通過在LinkedList
中獲取它們的位置來刪除ArrayList
中的重複項。如果您將輸入作爲a,a,a,a輸入,您會看到不會刪除重複項。誰能幫我?無法刪除ArrayList中的項目
import java.util.Scanner;
import java.util.LinkedList;
import java.util.ArrayList;
public class Duplicate2
{
public static void main(String[] args)
{
ArrayList <Character> list = new ArrayList<> (2);
Character y = 'A';
Scanner kb = new Scanner (System.in);
System.out.println("Enter 4 characters");
for(int n = 0; n <4; n++)
{
y = kb.next().charAt(0); // no matter how many character in a line, only the first is kept.
list.add(y);
}
System.out.println("Stop entering input.");
Duplicate2.removeDuplicate(list);
for (int n = 0; n < list.size(); n++)
System.out.println(list.get(n));
}
public static void removeDuplicate (ArrayList <Character> data)
{
int k = data.size();
int t = 0;
LinkedList <Integer> duplicatePosition = new LinkedList<>();
ArrayList <Character> copyList = new ArrayList <> (2);
for (int n = 0; n < data.size(); n ++)
{
Character x = data.get(n);
if (copyList.isEmpty())
copyList.add(x);
else
{
for (int m = 0; m <copyList.size(); m++)
{
if (x.equals(copyList.get(m)))
{
duplicatePosition.add(n);
t++;
break;
//data.remove(n);
}
else
{
copyList.add(x);
break;
}
}
}
}
System.out.println("Position of duplicate:");
for (int n = 0; n < duplicatePosition.size(); n++)
System.out.println(duplicatePosition.get(n));
System.out.println("Start to remove duplicates");
for (int n = 0; n< duplicatePosition.size(); n++)
{
System.out.println("Position " + duplicatePosition.get(n) + " would be removed.");
data.remove(duplicatePosition.get(n));
for (int m = 0; m < data.size(); m ++)
System.out.println(data.get(m));
if ((n+1)<duplicatePosition.size())
duplicatePosition.set(n+1, duplicatePosition.get(n+1) -1);
}
}
}