Card 02/ 09

ExampleDifficulty: Beginner1 min

Two Names for One Shopping Basket

A basket with one thing in it, and a second variable made from the first. Watch what happens to the original when you touch the copy.

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.

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.