Java Tutorials
Java Methods
Java Classes
Java File Handling
In the previous chapter, you learned about the ArrayList
class. The LinkedList
class is almost identical to ArrayList
:
// Import the LinkedList class
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
The LinkedList
section is a collection that may contain many items of the same type, such as ArrayList
.
The LinkedList
class has all the same features as the ArrayList
class because they both use the visual interface of the list. This means you can add items, change items, delete items and delete the list in the same way.
However, while the ArrayList
section and the LinkedList
section can be used in the same way, they are structured differently.
The ArrayList
class has a standard program within it. When an element is added, it is added to the same members. If the list is not enough, a new, larger system is built to replace the old one and replace the old one.
LinkedList
stores its contents in "containers." The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the feature is placed in a new container and that container is connected to one of the listed containers.
Use ArrayList
to store and access data, and LinkedList
to manage data.
In most cases, ArrayList
works very well as it often requires access to random items, but LinkedList
offers a few ways to perform certain tasks more effectively:
Method | Description | Try it |
---|---|---|
addFirst() | Adds an item to the beginning of the list. | |
addLast() | Add an item to the end of the list | |
removeFirst() | Remove an item from the beginning of the list. | |
removeLast() | Remove an item from the end of the list | |
getFirst() | Get the item at the beginning of the list | |
getLast() | Get the item at the end of the list |