列表如何在 Java 中工作?
public interface List<E> extends Collection<E>
List 接口扩展了Collection 并声明了存储元素序列的集合的行为。
可以使用基于零的索引通过其在列表中的位置来插入或访问元素。
列表可能包含重复元素。
除了Collection 定义的方法外,List 还定义了一些自己的方法,并在下表中进行了总结。
如果集合不能被修改,则几个 list 方法会抛出 UnsupportedOperationException,当一个对象与另一个对象不兼容时,会生成 ClassCastException。
示例
上述接口已在各种类中实现,例如 ArrayList 或 LinkedList 等。以下是示例,用来说明各种类实现上述集合方法的几种方法 -
package com.tutorialspoint;
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> a1 = new ArrayList<>();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println("ArrayList: " + a1);
List<String> l1 = new LinkedList<>();
l1.add("Zara");
l1.add("Mahnaz");
l1.add("Ayan");
l1.remove(1);
System.out.println("LinkedList: " + l1);
}
}输出
这将产生以下结果 -
ArrayList: [Zara, Mahnaz, Ayan] LinkedList: [Zara, Ayan]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP