0

When I pass this static method a linked list from main and remove the duplicates, the list remains un-changed. I assume this is because of some weird pass by value problem...Anyone know why?

public class LinkedListHelper{

public static <T> void eliminateDuplicates(LinkedList<T> list)
{
    LinkedList<T> temp = new LinkedList<>();
    temp.add(list.peekFirst()); //initialize this list with first element   
    ListIterator<T> itr1 = list.listIterator();
    ListIterator<T> itr2 = temp.listIterator();

    while(itr1.hasNext())
    {
        T element = itr1.next();
        boolean found = false;

        while(itr2.hasNext() && !found)
        {
            T current = itr2.next();            
            if(element == current)
                found = true;                   
        }

        if(!found)
            temp.add(element);

        itr2 = temp.listIterator();
    }

    list = temp; //Why does this not work????

}

}

user2499298
  • 177
  • 2
  • 5
  • 17
  • Because Java passes references by value, i.e. it creates a copy of the reference and passes this copy to the method. Affecting a new value to this copy won't change anything to the reference in the caller method. – JB Nizet Feb 20 '14 at 20:47

4 Answers4

1

There is no call-by-reference in Java that works like pointers in C/C++. Your parameter LinkedList<T> list ist not the reference variable you passed to the method, but rather a copy. You can change the data structure itself (that is, add, delete items etc.) but you cannot make the references refer to anpther list.

Instead, try myList = eliminateDuplicates(myList);

This, indeed, changes the actual reference.

exception1
  • 1,239
  • 8
  • 17
0

To make it work, you should not use a temp variable, but reference directly the list parameter. Also, you should modify the list referenced by the parameter, but not assign any value to the parameter because that shall make no effect on the variable named "list".

Andres
  • 10,561
  • 4
  • 45
  • 63
0

Because you created new list object, and at the and you just assigned a reference to variable list but the original list object was unchanged.

Add at the end instead of list = temp

list.clear();
list.addAll(tmep);

You also use == operator to check if objects are equal. Read about equals(Object) method

Smarter solution:

   <T> void eliminateDuplicates(LinkedList<T> list) {
    LinkedHashSet<T> set = new LinkedHashSet<T>();
    set.addAll(list);
    list.clear();
    list.addAll(set);
}
0

This happens because you only have a reference to the object, so you can't change its instance on the invoker. Altough, you can try removing everything and adding again

list.clear();
list.addAll(temp);
renke
  • 1,180
  • 2
  • 12
  • 27