List<E>
- Java course
- Intermediate
- Lesson 88/116
- 5 min
Learn generic lists with List<E>.
The List<E> interface
List<E> is the core interface of the Java collection framework. E is a type parameter that tells what the list holds. List<String> holds only strings, List<Integer> only integers.
The most common concrete implementation is ArrayList: List<String> names = new ArrayList<>();. The diamond <> on the right copies the left type. A List keeps insertion order; get(0) returns the first element.
List methods
Common list methods: add(e) appends, get(i) returns the element at index, set(i, e) replaces it, remove(i) deletes it, size() returns the count.
Example: names.add("Ayşe"); names.add("Alex"); String first = names.get(0);. Indices start at zero; names.get(0) returns the first element. indexOf(e) finds an element index or returns -1.
Practice Build a name list
Declare List<String> names = new ArrayList<>();. Add three names with names.add("Ayşe");, names.add("Alex"); and names.add("Mehmet");. Print the first name with System.out.println(names.get(0)); and the count with System.out.println(names.size());.
Starter code
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add three names, print first and count
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alex");
names.add("Mehmet");
System.out.println(names.get(0));
System.out.println(names.size());
}
}Expected output
Ayşe 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the list declaration
List<String> names = new ____<>();
List<String> names = new ArrayList<>();
Explanation: ArrayList is the common concrete implementation of List.
2 Match the List methods
| Term | Meaning |
|---|---|
add(e) |
Appends an element |
get(i) |
Returns the element at index |
set(i, e) |
Replaces the element at index |
size() |
Returns the element count |
3 What does names.get(0) return?
- The length of the list
- The first added element Correct answer
- The last added element
- The type parameter of the list
Explanation: get(0) returns the first element; List keeps insertion order.