Example 1 — Replace an Element and Keep the Old Value
Replace the second item of a list and print the value that was replaced.
import java.util.LinkedList;
public class LinkedListSetDemo {
public static void main(String[] args) {
LinkedList<String> menu = new LinkedList<>();
menu.add("soup");
menu.add("pasta");
menu.add("cake");
String old = menu.set(1, "pizza");
System.out.println("replaced: " + old);
System.out.println("menu: " + menu);
System.out.println("size: " + menu.size());
}
} How It Works
- Three dishes. "pasta" is at index 1.
- set swaps the value. "pizza" takes the place of "pasta" at index 1.
- The old value comes back.
oldholds "pasta", the element that was replaced. - The size is unchanged. There are still three dishes, because
setdoes not insert anything.

