Card 02/ 09

ExampleDifficulty: Beginner1 min

Reference Assignment Example: Two Names for One Shopping Basket

Add to the copy, print the original, and the item is there.

A List<String> is a list of strings, and a variable of that type is a reference variable: it holds the address of the list, not the list. Assigning one reference variable to another copies the address, so both names reach the same object. A basket with one thing in it, and a second variable made from the first:

java
List<String> basket = new ArrayList<>();
basket.add("apples");

List<String> sameBasket = basket;
sameBasket.add("bread");

System.out.println(basket);
text
[apples, bread]

Nothing was added to basket on line 6, and basket has two items in it. Line 4 copied what basket held, and what it held was an address. Now two variables carry the same address, and there is still exactly one list.

When you do want an independent copy, you ask for one: new ArrayList<>(basket) builds a second list holding the same items, and adding to it leaves basket alone.

This is the behaviour people describe as sharing, and it is not a special feature of lists. Every type with a capital letter behaves this way, because every one of them is reached through an address.