列表如何在 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