Q:

Method remove() from LinkedList doesn't work

I'm trying to make this simple Java exercise work, but it doesn't and I can't understand why.
Here is my code :
public LinkedList<T> toSet()
{
    LinkedList<T> retList; 
    retList = lista;
    for(T elem1 : retList)
        for(T elem2 :retList)
        {
            if(retList.indexOf(elem1) == retList.indexOf(elem2)) 
                continue;
            else if(elem1.equals(elem2)) 
                retList.remove(elem1);
        }

    return retList;
}

The method should remove the elements that appears more than one time in the list. I've debugged it with eclipse and I found that retList.remove(elem1) leaves the list unchanged!
Where is my mistake?

A:

You need to use .clone()
LinkedList<T> retList = (LinkedList<T>) lista.clone();
Also, you need to use iterators to remove from a LinkedList while in a loop. See this SO answer.

A:

The simple solution is to use a Set.  In your case you can use.
public Set<T> toSet() {
   return new LinkedHashSet<T>(lista);
}

