0
0
JavaConceptBeginner · 3 min read

What is List in Java: Explanation and Example

In Java, a 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.

java
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));
        }
    }
}
Output
Fruit at position 0: Apple Fruit at position 1: Banana Fruit at position 2: Apple
🎯

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: ArrayList and LinkedList.

Key Takeaways

A List in Java is an ordered collection that allows duplicates and access by position.
Use List when you need to keep items in sequence and retrieve them by index.
ArrayList is a common List type that stores items in a resizable array.
Lists are useful for tasks like managing ordered data such as names, tasks, or items.
You can add, remove, and update elements easily using List methods.