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
SetListIterator
is a class indirectly referenced by your code, but it is not on the classpath. When setting up your project you forgot to copy that source file in addition to SetListType
, or it could be that you are compiling this outside an IDE and simply failed to compile that class.
To answer the question "delete duplicates in java arraylist":
Just put all elements into a Set
and you're done.
-or-
Iterate your original
list and add the elements to a List
, but before adding them, check with List#contains()
if the element is already there.
EDIT: Try this:
String[] original = input.split(" ");
List<String> finalList = new ArrayList<String>();
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");
From what you're saying it sounds like when you run your assignment you are not setting your classpath correctly so that it includes the compiled class file of the SetListType. You should be able to fix this by setting the -classpath
option when running your main method to point to this and any other classes your assignment relies on.
You can use Vector or ListArray and check if the element exists in the new list before you add it.
Just an example:
Vector<String> list = new Vector<String>();
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<String> it = list.iterator();
Vector<String> newList = new Vector<String>();
while(it.hasNext()){
String s = it.next();
if(!newList.contains(s)){
newList.add(s);
}
}
for(String s : newList){
System.out.println(s);
}
For the second part:
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");
}