The List interface provides support for ordered collections of objects.
The List interface in Java is a part of the Java Collections Framework and is located in the java.util package. It extends the Collection interface and represents an ordered collection of elements. Unlike sets, lists typically allow duplicate elements.
Some key characteristics of the List interface include:
- Ordering: Lists maintain the order of elements in which they are inserted. This order can be the order of insertion or based on some other criteria, depending on the specific implementation of the List.
- Index-based Access: Elements in a List can be accessed using their index (position) in the list. The index starts from 0 for the first element.
- Duplicates: Unlike Set, a List can contain duplicate elements.
- Implementations: Java provides several classes that implement the List interface, such as ArrayList, LinkedList, and Vector.
Here’s a simple example of using the List interface in Java with an ArrayList:
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
// Creating a List using ArrayList
List<String> myList = new ArrayList<>();
// Adding elements to the List
myList.add("Java");
myList.add("Python");
myList.add("C++");
// Accessing elements using index
System.out.println("Element at index 1: " + myList.get(1));
// Iterating through the List
System.out.println("List elements:");
for (String element : myList) {
System.out.println(element);
}
}
}
In this example, ArrayList
is used to implement the List
interface, and basic operations like adding elements, accessing elements by index, and iterating through the list are demonstrated.