The LinkedList
class is almost identical to the ArrayList
:
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); } } // Outputs [Volvo, BMW, Ford, Mazda]
ArrayList vs. LinkedList
The ArrayList
class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.
The LinkedList
stores its items 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 element is placed into a new container and that container is linked to one of the other containers in the list.
Use an ArrayList
for storing and accessing data, and LinkedList
to manipulate data.
For many cases, the ArrayList
is more efficient as it is common to need access to random items in the list, but the LinkedList
provides several methods to do certain operations more efficiently:
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 |
标签:Java,LinkedList,cars,ArrayList,list,item,add From: https://www.cnblogs.com/ShengLiu/p/16928944.html