Java 提供了多种不同类型的 List 实现,其中一些常见的包括:
java.util.ArrayList
包。ArrayList
对象,通常使用无参构造函数: List<String> list = new ArrayList<>();
add()
方法添加元素: list.add("Item 1");
get()
方法获取元素: String item = list.get(0);
remove()
方法删除元素: list.remove(0);
import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Item 1");
list.add("Item 2");
String item = list.get(0);
System.out.println("First item: " + item);
list.remove(1);
System.out.println("List size after removal: " + list.size());
}
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
java.util.LinkedList
包。LinkedList
对象: List<Integer> linkedList = new LinkedList<>();
add()
方法添加元素: linkedList.add(10);
get()
方法获取元素: int value = linkedList.get(0);
remove()
方法删除元素: linkedList.remove(0);
import java.util.LinkedList;
import java.util.List;
public class LinkedListExample {
public static void main(String[] args) {
List<Integer> linkedList = new LinkedList<>();
linkedList.add(10);
linkedList.add(20);
int value = linkedList.get(0);
System.out.println("First value: " + value);
linkedList.remove(1);
System.out.println("List size after removal: " + linkedList.size());
}
}
java.util.Vector
包。Vector
对象: List<Double> vector = new Vector<>();
add()
方法添加元素: vector.add(3.14);
get()
方法获取元素: double number = vector.get(0);
remove()
方法删除元素: vector.remove(0);
import java.util.List;
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
List<Double> vector = new Vector<>();
vector.add(3.14);
vector.add(2.71);
double number = vector.get(0);
System.out.println("First number: " + number);
vector.remove(1);
System.out.println("List size after removal: " + vector.size());
}
}
这些示例代码涵盖了 ArrayList、LinkedList 和 Vector 三种常见的 List 实现方式。请根据项目的需求和性能特点选择合适的实现方式。