Im trying to work on an assignment question for my intro java course where we are supposed to remove duplicate items from a list without using sets or the .contains() method. Basically just using iterators and the .equals() method. My code is as follows:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class sample {
public static void main(String[] args) throws BadListException {
List<String> myList = new ArrayList<String>();
myList.add("A");
myList.add("B");
myList.add("B");
myList.add("C");
myList.add("B");
myList.add("D");
unique(myList);
System.out.println(myList);
}
public static List<String> unique( List<String> items ) throws BadListException {
List<String> newList = new ArrayList<String>();
Iterator<String> itr = items.listIterator();
// If items is null, throw a BadListException.
if (items == null){
throw new BadListException();
}
// If items is empty, return a new empty list.
if (items.isEmpty()){
return newList;
}
// Otherwise create and return a new list that contains the items
// in L with all duplicates removed.
// Example: items: "A","B","C" result: "A","B","C"
// Example: items: "A","A","A" result: "A"
// Example: items: "A","B","B","C","A","D" result: "A","B","C","D"
while (itr.hasNext()){
for (int i = 0; i < items.size()-1; i++){
if (itr.next().equals(items.get(i))){
itr.remove();
}
}
}
items = newList;
return newList;
If someone could please explain what I'm doing wrong and how I should go about doing it instead that would be very helpful. Please note that since this is to prepare me for a test I would appreciate an explanation rather than just the correct piece of code.
Rather than explaining exactly what is going wrong, I'm going to suggest that you use a debugger to see what the program is currently doing. In particular, look at what the iterator is returning each time you call iter.next().
Hints for a correct solution:
In future, when you ask a question, you should provide a better statement of what the program is actually supposed to do. For instance:
unique method is supposed to remove elements from the argument list or return a new list containing (just) the unique elements.All of these things matter in deciding how to solve a problem like this. Especially in the real world. Even your assignment did not state these things, you still need to make up your own mind how your code is intended to work ... and document this with javadoc comments.
i==0 your iterator.next() and get(i) would be the same element, so you just removed it.iterator.remove() within a for loop. add anything to the newList, and returned it simplyyou could first sort the list, then go through it, if an element is equal to its previous one, remove the element. You could of course create a new list to hold those unique elements if you want.
my 2 cents
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With