Thanks Marko. I rewrite the code. try to make it simple. this time it can really compile. but it can only delete duplicate items sit next to each other. for example, if i put in 1 2 3 3 4 4 5 1 — the output is 1 2 3 4 5 1. it can’t pick up the duplicate at the end.
(BTW: new to this website, if make any display mess my apologies)
here’s the new code:
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<String> finalList = new ArrayList(Arrays.asList(original)) ;
Iterator<String> 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) + ", ");
}
}
To answer the question “delete duplicates in java arraylist”:
Just put all elements into a
Setand you’re done.-or-
Iterate your
originallist and add the elements to aList, but before adding them, check withList#contains()if the element is already there.EDIT: Try this: