How to write a method that recieves an ADT and removes duplicates?

328 views Asked by At

We are given an implementation of the genericSackADT (code below) that implements the iterable interface.

public interface GSackIterableADT<T> extends Iterable<T> {
        void add(T item);
        T remove() throws NoSuchElementException;
        boolean isEmpty();
        Iterator<T> iterator();

We are supposed to write a method that can accept this as input and remove all duplicates.

I think I need some conceptual guidance on this. My plan right now is to create a method called removeDuplicates that uses an iterator to scan through the ADT and remove duplicates when they are found. I checked the iterator API and I should be able to use E next () and void remove () to do this, correct? However, my code is a mess right now and I'm not sure where exactly to go...

public static <E> int removeDuplicates (match) {
        int counter = 0;
        ListIterator<E> iter = myList.listiterator();
        while (iter.hasNext());
        E val = iter.next();
        //the goal in the next step is to remove duplicates as the iterator finds them
        if (val.equals(match){
            void remove()
1

There are 1 answers

0
Tim Biegeleisen On

One easy way to remove duplicates is to add your collection to a Set, and then convert it back to a List. The Java Set implementations will automatically remove duplicates during an add() operation. I assume your implementation is using a List under the hood telling from your sample code.

public static List<E> removeDuplicates (List<E> inputList) {
    int dupCount = 0;
    Set<E> listSet = new HashSet<E>();
    ListIterator<E> iter = inputList.listIterator();
    while (iter.hasNext()) {
        E val = iter.next();
        if (!listSet.add(val)) {
            ++dupCount;
        }
    }

    // you can log the number of duplicates if you want

    List<E> newList = Arrays.asList(listSet.toArray());

    return newList;
}