删除java arraylist中的重复项

谢谢Marko。 我重写了代码。 尽量使它变得简单。 这次它真的可以编译。 但它只能删除重复的项目彼此相邻。 例如,如果我输入1 2 3 3 4 4 5 1 – 输出为1 2 3 4 5 1.它最终无法获取副本。 (顺便说一句:这个网站的新手,如果让任何显示混乱我的道歉)

这是新代码:

import java.util.*; public class SetListDemo{ public static void main(String[] args){ SetListType newList = new SetListType(); Scanner keyboard = new Scanner(System.in); System.out.println( "Enter a series of items: "); String input = keyboard.nextLine(); String[] original = input.split(" "); for (String s : original) newList.insert(s); List finalList = new ArrayList(Arrays.asList(original)) ; Iterator setIterator = finalList.iterator(); String position = null; while(setIterator.hasNext()){ String secondItem = setIterator.next(); if(secondItem.equals(position)){ setIterator.remove(); } position = secondItem; } System.out.println("\nHere is the set list:"); displayList(finalList); System.out.println("\n"); } public static void displayList(List list){ for(int index = 0; index <list.size(); index++) System.out.print(list.get(index) + ", "); } } 

要回答“删除java arraylist中的重复项”的问题:

只需将所有元素放入Set完成。

-要么-

迭代original列表并将元素添加到List ,但在添加它们之前,如果元素已经存在,请检查List#contains()

编辑:试试这个:

 String[] original = input.split(" "); List finalList = new ArrayList(); for (String s : original) { if (!finalList.contains(s)) { finalList.add(s); } } System.out.println("\nHere is the set list:"); displayList(finalList); System.out.println("\n"); 

SetListIterator是您的代码间接引用的类,但它不在类路径中。 在设置项目时,除了SetListType之外,您忘记复制该源文件,或者可能是您在IDE外部编译它并且无法编译该类。

从你的说法来看,这听起来就像你运行你的作业时你没有正确设置你的类路径,所以它包括SetListType的编译类文件。 您应该能够通过在运行main方法时设置-classpath选项以指向此以及您的分配所依赖的任何其他类来解决此问题。

您可以使用Vector或ListArray并在添加之前检查新列表中是否存在该元素。

举个例子:

  Vector list = new Vector(); System.out.println("list:"); for(int i=0; i<100; i++){ list.add("" + new Random().nextInt(10)); System.out.println(list.lastElement()); } System.out.println("newList:"); java.util.Iterator it = list.iterator(); Vector newList = new Vector(); while(it.hasNext()){ String s = it.next(); if(!newList.contains(s)){ newList.add(s); } } for(String s : newList){ System.out.println(s); } 

第二部分:

  int[] count = new int[newList.size()]; for(String s : list){ int index = newList.indexOf(s); count[index]++; } for(String s : newList){ System.out.println(s + " appears " + count[newList.indexOf(s)] + " times"); }