Java – Linked list clarification

javalinked list

This is a pretty simple question but I'm new to java.

The linked list found in java.util.LinkedList.

I saw elsewhere that Java does not use pointers…

When I create a new list and add new elements to it, does the list contain references to the data and to the next/previous elements or does it also contain the object itself.

Best Answer

In Java you have primitives (int, long, etc.) and objects. Objects are references (pointers) to complex data.

Java always passes values; so within your list you will have actual values of what you put in. BUT: Since objects are references to data, the values passed will be the references, not the data itself.

Pragmatic result: You put object A in a list and change its data somewhere in your code. Object A will still be in your list (you didn't change A but its data) but the A in your list will reflect the changes you've made somewhere else.

Car a = new Car();
List myList = new LinkedList();
myList.add(a);
a.driveHome();
Car carFromList = myList.getFirst();
carFromList.isDrivenHome(); // true