'How to pass a Linked list as a function parameter in java

I am struggling in "How to pass a Linked list as a function parameter" in java. This method is supposed to take another linked list as a parameter, and add the contents of this linked list to the calling instance's linked list. Adding the elements should only be done if the element does not already exist. All elements to be added should be added at the end of the linked list.



Solution 1:[1]

In Java every parameter which is not of primitive type (int, long, byte, char, boolean...) is passed as a reference to that object.

Here's a simple example:

public static void main(String[] args){
   List<?> myList = new ArrayList<>();
   myList.add(1);
   myList.add("Sarah");
   process(myList);
   Iterator it = myList.iterator();
   while(it.hasNext()){
      System.out.println(it.next());
   }
}

public static void process(List<?> list){
 list.add("Johnny");
}

The output will be:

1
Sarah
Johnny

Meaning the list you passed as parameter is actually passed by reference hence "Johnny" gets added.

This applies to any real object (extends Object).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 StackFlowed