Java LinkedList
A LinkedList is a list that links each item to the next one. It adds and removes items at the ends with dedicated methods.
Add items to a LinkedList
add appends each name at the end. The size line counts three items.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<String>();
names.add("Ada");
names.add("Ben");
names.add("Cid");
System.out.println(names.get(0));
System.out.println(names.size());
}
}Add at both ends
addFirst puts Ada at the front. addLast puts Zoe at the back.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<String>();
names.add("Mia");
names.addFirst("Ada");
names.addLast("Zoe");
System.out.println(names.getFirst());
System.out.println(names.getLast());
}
}Remove the first item
removeFirst drops Ada from the front. Ben becomes the new first item.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<String>();
names.add("Ada");
names.add("Ben");
names.add("Cid");
names.removeFirst();
System.out.println(names.getFirst());
System.out.println(names.size());
}
}Example
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> line = new LinkedList<String>();
line.add("Ben");
line.add("Cid");
line.addFirst("Ada");
line.addLast("Dee");
line.removeFirst();
System.out.println(line.getFirst());
System.out.println(line.getLast());
for (String name : line) {
System.out.println(name);
}
}
}Key points
- LinkedList lives in java.util and is imported before use.
- add appends an item at the end of the list.
- addFirst and addLast place an item at a chosen end.
- getFirst and getLast read the items at the ends.
- removeFirst removes the first item from the list.
- The angle brackets name the type the list holds.
In this example, the list starts with Ben and Cid. addFirst places Ada at the front and addLast places Dee at the back. removeFirst then drops Ada. The ends now read Ben and Dee, and the loop prints the three remaining names.
Note
LinkedList offers the same add, get, set, remove, and size methods as ArrayList.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method adds an item at the front of a LinkedList?