Sobes.tech
Junior

What is a list (List) in Java?

sobes.tech AI

Answer from AI

List in Java is an ordered collection of elements that allows duplicates. Elements have an index starting from 0.

Main characteristics:

  • Orderliness: maintains the order of element addition.
  • Duplicates: allows storing identical elements.
  • Access by index: provides quick access to elements by their numerical index.

The List interface is a descendant of the Collection interface. The most common implementations:

  • ArrayList: Dynamic array, suitable for frequent access to elements by index.
  • LinkedList: List based on doubly linked nodes, efficient for frequent insertions and deletions at the beginning or end of the list.
  • Vector: Synchronized version of ArrayList, deprecated.

Example of usage:

// Creating an ArrayList
List<String> fruits = new ArrayList<>();

// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // Adding a duplicate

// Accessing an element by index
String firstFruit = fruits.get(0); // "Apple"

// List size
int size = fruits.size(); // 4

// Iterating over elements
for (String fruit : fruits) {
    // ...
}
What is a list (List) in Java? — Java - sobes.tech