In Java, the java.util
package provides several classes for implementing lists. Two commonly used implementations are LinkedList
and Array List
.
Here’s an overview of Linked List and Array List:
- LinkedList:
java.util.LinkedList
implements theList
interface using a doubly-linked list.- Each element in the list is stored as a separate object (node) containing a reference to the previous and next elements in the list.
- Insertion and deletion operations can be performed efficiently at any position in the list.
- Traversal might be slower compared to arrays because elements are not stored in contiguous memory locations.
- Suitable for scenarios where frequent insertion and deletion operations are required, especially near the beginning or middle of the list.
- Not suitable for random access operations (i.e., accessing elements by index) due to slower traversal.
- ArrayList:
java.util.ArrayList
implements theList
interface using a dynamic array.- Elements are stored in a contiguous memory block, allowing for efficient random access using indexes.
- Insertion and deletion operations at the end of the list are efficient. However, inserting or removing elements from the middle of the list requires shifting subsequent elements, which can be costly.
- Suitable for scenarios where frequent random access and traversal operations are required.
- Offers better performance for accessing elements by index compared to
LinkedList
. - Automatically grows its internal array when needed to accommodate more elements.
Here’s an example demonstrating the usage of LinkedList
and ArrayList
:
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// LinkedList Example
List<String> linkedList = new LinkedList<>();
linkedList.add("Apple");
linkedList.add("Banana");
linkedList.add("Orange");
System.out.println("LinkedList:");
for (String fruit : linkedList) {
System.out.println(fruit);
}
// ArrayList Example
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");
System.out.println("\nArrayList:");
for (String fruit : arrayList) {
System.out.println(fruit);
}
}
}