Say I have a linked list called L that stores linked lists so:
LinkedList <LinkedList<String>> L
if I do L1 = L.getLast() can I also say L.getLast.add("something") or L1.add("something") and will that add “something” to the last list or only the local instance of that list?
What do you mean by “local instance of that list”? We’re dealing with reference types here – what’s stored in the outer list is simply references to instances of lists. When you fetch the last element, that just gets you a copy of a reference. It doesn’t matter how you access the object, you’re still modifying that single object.
You’ve made your example more complicated than it needs to be by creating a
LinkedList<LinkedList<String>>, but fundamentally this is the same issue as we can easily demonstrate with aStringBuilder:Again, we’ve got a single
StringBuilderobject, and the values of bothxandyare references to that same object. It doesn’t matter how you modify it, the modification will be visible however you then access the object.Or if you want to use lists as an example:
This is crucial to understanding Java – all classes work the same way. The value of an expression is never an object; it’s always either a reference or a primitive value.