Sub topic 9
Repositioning elements with addFirst, addLast, putFirst and putLast
This chapter assumes you know the core java.util collections (List, Set, Map, Deque) and the difference between ordered, sorted and unordered collections. It also assumes you have met SequencedCollection, SequencedSet and SequencedMap from the earlier chapters, and that you run Java 21 or newer.
The methods addFirst, addLast, putFirst and putLast look like simple insertion operations. On lists and deques they are. On sets and maps that must keep elements unique, they also move entries that are already present, which add and put never do. This chapter covers that behavior, the cases where the methods throw, and how to use them safely.
Plain insertion does not reposition
Before Java 21, a LinkedHashSet or an insertion-ordered LinkedHashMap kept the position of the first insertion. Adding a duplicate did nothing. Putting an existing key replaced the value but left the entry where it was. The LinkedHashSet documentation calls this: "Note that insertion order is not affected if an element is re-inserted into the set."
That rule makes it hard to express "move this to the front" or "this is now the most recent". You had to remove the element and add it again:
set.remove(x);
set.add(x); // x is now lastThat works for moving to the end. Moving to the front had no clean idiom on a LinkedHashSet. You had to rebuild the set.
Java 21 adds methods whose contract is to place the element at a given end, whether or not it was already present.
LinkedHashSet: addFirst and addLast
SequencedCollection declares addFirst(E) and addLast(E), both returning void. For LinkedHashSet the documented behavior is:
- If the element is not present, it is inserted at the requested end.
- If the element is already present, it moves to the requested end. The set's size does not change.
The following program compares add with the new methods:
import java.util.LinkedHashSet;
import java.util.List;
public class SetReposition2 {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>(List.of("a", "b", "c"));
boolean changed = set.add("a"); // already present
System.out.println(changed); // false
System.out.println(set); // [a, b, c]
set.addLast("a"); // a moves to the end
System.out.println(set); // [b, c, a]
set.addFirst("c"); // c moves to the front
System.out.println(set); // [c, b, a]
set.addFirst("z"); // new element goes to the front
System.out.println(set); // [z, c, b, a]
}
}Two details matter here:
addreturnsfalsewhen the element is already present.addFirstandaddLastreturn nothing, so you cannot tell from the result whether the set grew. Checkcontainsor compare sizes first if you need to know.- Membership still follows
equalsandhashCode, as with every hash-based set. An element that equals an existing one counts as present.
The next diagram shows the decision that addFirst makes in a LinkedHashSet.
Repositioning is cheap. A LinkedHashSet stores a doubly linked list through its hash entries, so moving an entry means relinking a few pointers, which is constant time.
LinkedHashMap: putFirst and putLast
SequencedMap declares putFirst(K, V) and putLast(K, V). Unlike the collection methods, they return the previous value for the key, or null if there was none. This matches put.
LinkedHashMap implements them like this:
- If the key is absent, a new mapping is inserted at the requested end.
- If the key is present, the value is replaced and the entry moves to the requested end.
import java.util.LinkedHashMap;
public class MapReposition {
public static void main(String[] args) {
LinkedHashMap<String, Integer> m = new LinkedHashMap<>();
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
m.put("a", 10); // value changes, position does not
System.out.println(m); // {a=10, b=2, c=3}
Integer old = m.putLast("a", 11); // value changes and entry moves
System.out.println(old); // 10
System.out.println(m); // {b=2, c=3, a=11}
old = m.putFirst("c", 30);
System.out.println(old); // 3
System.out.println(m); // {c=30, b=2, a=11}
old = m.putFirst("z", 0); // new key
System.out.println(old); // null
System.out.println(m); // {z=0, c=30, b=2, a=11}
}
}The key point is that put and putLast can give different orders for the same existing key. Use putLast when you mean "this entry is now the newest", and put when you only want to update a value in place.
If the old value was legitimately null, a null return does not tell you whether the key existed. Use containsKey first if you need to distinguish the two.
Access-ordered maps
A LinkedHashMap built with accessOrder = true already moves an entry to the end when you call get or put on it. That mode is the classic base for LRU caches. Because get reorders entries there, such a map changes shape during reads. If you mix that mode with explicit putFirst and putLast calls, order depends on both rules. Prefer insertion-ordered maps when you want to control order with these methods.
A worked example: a bounded recent-items list
A common use is a "recently used" list that keeps unique entries, newest first, and drops the oldest when full. Before Java 21 this needed remove followed by add, plus code to read the oldest element. With sequenced methods it is short:
import java.util.LinkedHashSet;
import java.util.SequencedSet;
public class RecentItems {
private final SequencedSet<String> items = new LinkedHashSet<>();
private final int capacity;
RecentItems(int capacity) {
this.capacity = capacity;
}
void touch(String item) {
items.addFirst(item); // new or existing: now the newest
if (items.size() > capacity) {
items.removeLast(); // drop the oldest
}
}
public static void main(String[] args) {
RecentItems recent = new RecentItems(3);
for (String s : new String[] {"a", "b", "c", "a", "d"}) {
recent.touch(s);
System.out.println(recent.items);
}
// [a]
// [b, a]
// [c, b, a]
// [a, c, b]
// [d, a, c]
}
}Trace the fourth call. a is already in the set, so addFirst moves it to the front and the size stays at 3. Nothing is evicted. On the fifth call d is new, so the size reaches 4 and removeLast drops b.
The field is declared as SequencedSet<String>, not LinkedHashSet<String>. The code only needs the interface, so any implementation with a defined order that supports addFirst would work.
Repositioning through reversed views
A reversed view swaps the meaning of first and last. A call on the view is translated into the opposite call on the original:
| Call on the reversed view | Equivalent call on the original |
|---|---|
| `addFirst(e)` | `addLast(e)` |
| `addLast(e)` | `addFirst(e)` |
| `putFirst(k, v)` | `putLast(k, v)` |
| `putLast(k, v)` | `putFirst(k, v)` |
The repositioning rules carry over unchanged:
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
public class ReversedReposition {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>(List.of("a", "b", "c"));
SequencedSet<String> rev = set.reversed();
rev.addFirst("x"); // front of the view is the end of the original
System.out.println(set); // [a, b, c, x]
System.out.println(rev); // [x, c, b, a]
rev.addLast("b"); // existing element moves to the front of the original
System.out.println(set); // [b, a, c, x]
}
}Which types support these methods
The default implementations in the interfaces throw UnsupportedOperationException. Each class decides whether it overrides them. The table below summarizes the common JDK types.
| Type | addFirst / addLast (putFirst / putLast) | Behavior |
|---|---|---|
| `ArrayList` | supported | Inserts at index 0 or at the end. Duplicates are allowed, so nothing moves. Insertion at the front is linear time. |
| `LinkedList` | supported | Inserts at either end in constant time. Duplicates are allowed. |
| `ArrayDeque` | supported | Inserts at either end in constant time. Rejects `null` with `NullPointerException`. |
| `LinkedHashSet` | supported | Inserts or moves the element to the requested end. |
| `LinkedHashMap` | supported | Inserts or moves the entry to the requested end and replaces the value. |
| `TreeSet` | throws `UnsupportedOperationException` | The comparator decides the position. |
| `TreeMap` | throws `UnsupportedOperationException` | The comparator decides the position. |
| `List.of(...)`, `Collections.unmodifiable*` | throws `UnsupportedOperationException` | The collection is read-only. |
The list and deque rows are not "repositioning" at all. ArrayList.addFirst always adds a new element, so after addFirst("a") on a list that already holds "a" you have two copies. Only the set and map implementations treat a repeated element or key as a move.
The following program shows the exceptions:
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
import java.util.TreeMap;
import java.util.TreeSet;
public class Unsupported {
public static void main(String[] args) {
try {
new TreeSet<>(List.of(3, 1, 2)).addFirst(0);
} catch (UnsupportedOperationException e) {
System.out.println("TreeSet.addFirst is unsupported");
}
try {
new TreeMap<String, Integer>().putLast("k", 1);
} catch (UnsupportedOperationException e) {
System.out.println("TreeMap.putLast is unsupported");
}
SequencedSet<String> ro =
Collections.unmodifiableSequencedSet(new LinkedHashSet<>(List.of("a", "b")));
try {
ro.addLast("c");
} catch (UnsupportedOperationException e) {
System.out.println("read-only wrapper rejects addLast");
}
}
}Pitfalls
- Expecting
addto move. Code that callsaddorputon an existing element and expects a new position keeps the old position. Switch toaddLastorputLastwhen you mean "most recent". - Ignoring the return value of
putFirstandputLast. The returned previous value is the only signal that you replaced something. - Repositioning while iterating. Moving entries changes the structure of the linked order. Do not call these methods on a collection while you iterate over it. Doing so may throw
ConcurrentModificationException. Collect the changes first and apply them after the loop. - Assuming other sets behave this way.
HashSetandSet.ofhave no order, andTreeSethas a comparator order. OnlyLinkedHashSetandLinkedHashMapsupport moves. - Sharing a view and its original across threads. The view is not a separate copy, so a repositioning call on it changes the original. Neither type is thread safe.
Exercise
A LinkedHashMap<String, Integer> contains {x=1, y=2, z=3}. You run map.put("x", 5), then map.putLast("y", 6), then map.putFirst("w", 7). What is the map afterward, and what does each of the three calls return?
Show answer
The final map is {w=7, z=3, x=5, y=6}. put("x", 5) returns 1 and leaves x in place, giving {x=5, y=2, z=3}. putLast("y", 6) returns 2 and moves y to the end, giving {x=5, z=3, y=6}. putFirst("w", 7) returns null because w was absent, and inserts it at the front, giving {w=7, x=5, z=3, y=6}. Rechecking the order: x came before z before y, so the final order is {w=7, x=5, z=3, y=6}.
Exercise
You have a LinkedHashSet<String> named set holding [a, b, c] and var rev = set.reversed();. After rev.addLast("c") followed by rev.addFirst("a"), what does set contain? Then say what happens if set is replaced by a TreeSet<String>.
Show answer
rev.addLast("c") is set.addFirst("c"), so set becomes [c, a, b]. rev.addFirst("a") is set.addLast("a"), so set becomes [c, b, a]. With a TreeSet, both calls throw UnsupportedOperationException, because its comparator decides element positions and no end can be requested.
Exercise
Why does ArrayList.addFirst("a") on a list that already contains "a" not behave like LinkedHashSet.addFirst("a")?
Show answer
A list allows duplicates and has no uniqueness rule, so ArrayList.addFirst always inserts a new element at index 0 and the list grows by one. A LinkedHashSet forbids duplicates, so when the element exists it is moved to the front and the size stays the same.