Java中的
List
是一种有序的数据容器,它可以存储任意类型的元素,并且支持重复元素。
1. List接口
首先我们来介绍一下List
接口。
public interface List<E> extends Collection<E> {
// 添加元素
boolean add(E e);
void add(int index, E element);
// 删除元素
E remove(int index);
boolean remove(Object o);
// 获取元素
E get(int index);
// 更新元素
E set(int index, E element);
// 查询元素位置
int indexOf(Object o);
int lastIndexOf(Object o);
// 截取子列表
List<E> subList(int fromIndex, int toIndex);
}
List
接口继承了Collection
接口,提供了一系列操作集合元素的方法,包括添加、删除、获取、更新等。此外,List
还提供了查询元素位置和截取子列表等方法。
2. ArrayList类
ArrayList
是List
接口的一个常用实现类,其内部采用数组实现。
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable{
// 构造函数
public ArrayList();
public ArrayList(int initialCapacity);
public ArrayList(Collection<? extends E> c);
// 添加元素
public boolean add(E e);
public void add(int index, E element);
public boolean addAll(Collection<? extends E> c);
public boolean addAll(int index, Collection<? extends E> c);
// 删除元素
public void clear();
public E remove(int index);
public boolean remove(Object o);
protected void removeRange(int fromIndex, int toIndex);
// 获取元素
public E get(int index);
// 更新元素
public E set(int index, E element);
// 查询元素位置
public int indexOf(Object o);
public int lastIndexOf(Object o);
// 截取子列表
public List<E> subList(int fromIndex, int toIndex);
}
ArrayList
实现了List
接口,同时还继承了抽象类AbstractList
,实现了RandomAccess
接口、Cloneable
接口和Serializable
接口等。它提供了一系列操作集合元素的方法,包括添加、删除、获取、更新等。
3. LinkedList类
LinkedList
是List
接口的另一个常用实现类,其内部采用链表实现。
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable {
// 构造函数
public LinkedList();
public LinkedList(Collection<? extends E> c);
// 添加元素
public boolean add(E e);
public void add(int index, E element);
public boolean addAll(Collection<? extends E> c);
public boolean addAll(int index, Collection<? extends E> c);
// 删除元素
public void clear();
public E remove(int index);
public boolean remove(Object o);
// 获取元素
public E get(int index);
// 更新元素
public E set(int index, E element);
// 查询元素位置
public int indexOf(Object o);
public int lastIndexOf(Object o);
// 截取子列表
public List<E> subList(int fromIndex, int toIndex);
}
LinkedList
同样实现了List
接口,同时还继承了抽象类AbstractSequentialList
,实现了Deque
接口、Cloneable
接口和Serializable
接口等。与ArrayList
不同,它内部采用链表结构实现。
4. 总结
在Java中,
List
接口是一个常用的数据容器,提供了一系列操作集合元素的方法。其中,ArrayList
和LinkedList
分别是两种常用的实现方式,在使用时需要根据具体情况进行选择。