List 接口扩展Collection 并声明存储元素序列的集合的行为。

  • 可以使用从零开始的索引,通过元素在列表中的位置插入或访问元素。

  • 列表可以包含重复的元素。

  • 除了Collection定义的方法之外,List还定义了一些自己的方法,下表总结了这些方法。

  • 如果集合无法修改,多个列表方法将抛出 UnsupportedOperationException,并且当一个对象与另一个对象不兼容时会生成 ClassCastException。

序号方法 &描述
1

void add(int index, Object obj)

插入obj 进入调用列表中传入索引的索引处。插入点处或插入点之外的任何预先存在的元素都会上移。因此,不会覆盖任何元素。

2

boolean addAll(int index, Collection c)

c 的所有元素插入调用列表中传入索引的索引处。插入点处或插入点之外的任何预先存在的元素都会上移。因此,没有元素被覆盖。如果调用列表发生更改,则返回 true,否则返回 false。

3

Object get(int index)

返回调用集合中指定索引处存储的对象。

4

int indexOf(Object obj)

返回调用列表中第一个 obj 实例的索引。如果 obj 不是列表的元素,则返回 .1。

5

int lastIndexOf(对象 obj)

返回调用列表中最后一个 obj 实例的索引。如果 obj 不是列表的元素,则返回 .1。

6

ListIterator listIterator( )

返回一个迭代器到调用列表的开头。

7

ListIterator listIterator(int index)

返回一个迭代器到从指定索引开始的调用列表。

8

Object remove(int index)

从调用列表中删除位置index处的元素并返回删除的元素。结果列表被压缩。即后续元素的索引减一。

9

Object set(int index , Object obj)

将 obj 分配给调用列表中索引指定的位置。

10

List subList(int start, int end)

返回一个列表,其中包含调用列表中从 start 到 end.1 的元素。返回列表中的元素也被调用对象引用。

示例1

上面的接口已经使用ArrayList实现。下面通过示例来解释上述集合方法的各种类实现中的几个方法 -

import java.util.ArrayList;
import java.util.List;
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 Elements");
      System.out.print("\t" + a1);
   }
} 

输出

ArrayList Elements
   [Zara, Mahnaz, Ayan] 

示例 2

上述接口已实现使用链表。下面通过示例来解释上述集合方法的各种类实现中的几个方法 -

import java.util.LinkedList;
import java.util.List;
public class CollectionsDemo {

   public static void main(String[] args) {
      List<String> a1 = new LinkedList<>();
      a1.add("Zara");
      a1.add("Mahnaz");
      a1.add("Ayan");      
      System.out.println(" LinkedList Elements");
      System.out.print("\t" + a1);
   }
} 

输出

LinkedList Elements
   [Zara, Mahnaz, Ayan] 

示例 3

上述接口已实现使用数组列表。以下是另一个示例,解释上述集合方法的各种类实现中的一些方法 -

import java.util.ArrayList;
import java.util.List;
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 Elements");
      System.out.print("\t" + a1);
      
      //删除第二个元素
      a1.remove(1);
      
      System.out.println("\n ArrayList Elements");
      System.out.print("\t" + a1);
   }
} 

Output

ArrayList Elements
   [Zara, Mahnaz, Ayan]
 ArrayList Elements
   [Zara, Ayan]