What is List in Java: Explanation and Example
List is an ordered collection that can hold elements in a sequence. It allows duplicates and provides methods to add, remove, and access elements by their position.How It Works
Think of a List in Java like a row of boxes where you can store items one after another. Each box has a position number starting from zero, so you can easily find or change the item in any box by its position.
Unlike some collections, a List keeps the order of items exactly as you add them. You can also have the same item more than once, just like having multiple identical books on a shelf.
Java provides different types of lists, such as ArrayList and LinkedList, each with its own way of storing and managing these boxes behind the scenes.
Example
This example shows how to create a List of strings, add items, and print them out.
import java.util.List; import java.util.ArrayList; public class ListExample { public static void main(String[] args) { List<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Apple"); // duplicate allowed for (int i = 0; i < fruits.size(); i++) { System.out.println("Fruit at position " + i + ": " + fruits.get(i)); } } }
When to Use
Use a List when you need to keep items in order and want to access them by their position. It is great for tasks like storing a list of names, shopping items, or any collection where duplicates are allowed and order matters.
For example, if you are making a to-do app, a List can hold tasks in the order they were added, so users see them in the right sequence.
Key Points
- Ordered: Items keep the order you add them.
- Duplicates allowed: Same item can appear multiple times.
- Access by index: You can get or change items by their position.
- Common implementations:
ArrayListandLinkedList.