The Java collection framework provides an List
interface for storing an ordered set of elements. List
Elements in are repeatable and can be accessed by index. If you are familiar with arrays, you can List
think of them as a kind of dynamic array.
List
Interfaces have many implementation classes, some of the more common ones include:
ArrayList
: Based on a dynamic array implementation, the search and access speeds are fast, and the insertion and deletion speeds are relatively slow;LinkedList
: Based on linked list implementation, insertion and deletion are fast, but access speed is slow;Vector
:ArrayList
Similar to, but thread-safe, so it is safer to use in a multi-threaded environment;Stack
: Inherited fromVector
, provides last-in-first-out (LIFO) stack structure.
List
The interface defines the methods to operate on the list, commonly used include:
add(E e)
: Adds an element to the end of the list.get(int index)
: Returns the element at the specified position.remove(int index)
: Remove the element at the specified position.size()
: Returns the number of elements in the list.
In addition to these basic operations, List
some other operations are provided, such as sorting, searching, sublisting, etc. These operations can be implemented through the methods of Collections
the class or List
interface itself.
In short, List
it is a very important and commonly used type in the Java collection framework, which can easily manage and operate a set of ordered data.
The Java collection framework provides an List
interface for storing an ordered set of elements. List
Elements in can be repeated and can be accessed by subscript. If you are familiar with arrays, you can think List
of them as a dynamic array.
Here is a simple example showing how to create one List
and add elements:
javaCopy code
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); System.out.println(list); } }
This program will output: [apple, banana, orange]
.
Note that List
it is an interface and cannot be instantiated directly. In the above example, we used ArrayList
classes to implement List
interfaces.
List
The interface provides many methods to manipulate lists. Here are some commonly used methods:
add(E e)
- Adds an element to the end of the list.get(int index)
- Returns the element at the specified position.remove(int index)
- Removes the element at the specified position.size()
- Returns the number of elements in the list.