List
有序集合,可以精确控制每个元素在列表中的插入位置。用户可以通过其整数索引(在列表中的位置)访问元素,并在列表中搜索元素,列表通常允许重复元素,使用e1.equals(e2)来表示e1和e2相等。
1.接口的定义
public interface List<E> extends Collection<E> {
// 1.继承至Collection接口
// 2.E作为泛型存在
}
2.主要方法
public interface List<E> extends Collection<E> {
// 返回集合中元素的个数
int size();
// 集合中没有元素,则返回true
boolean isEmpty();
// 集合中包含o,则返回true,o的类型并不是E,判断相同时常用equals()方法
boolean contains(Object o);
// 产生迭代器
Iterator<E> iterator();
// 增加元素,增加成功则返回ture
boolean add(E e);
// 删除元素,删除成功则返回true,使用equals()方法来判断两个元素是否相同
boolean remove(Object o);
// 此集合中包含指定集合中的所有元素,则返回true
boolean containsAll(Collection<?> c);
// 将指定集合中的所有元素添加到此集合中
boolean addAll(Colleciont<? extends E> c);
// 删除指定集合中也包含此集合的所有元素
boolean removeAll(Collection<?> c);
// 仅此保留此集合中包含指定集合中的元素
boolean retainAll(Collection<?> c);
// 删除所有元素
void clear();
// 排序
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
// 返回集合中指定位置的元素
E get(int index);
// 替换指定位置的元素
E set(int index,E element);
// 在指定位置插入元素
void add(int index,E element);
// 删除指定位置的元素
E remove(int index);
// 返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回-1
int indexOf(Object o);
// 返回此列表中指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-1
int indexIndexOf(Object o);
// 返回从fromIndex到toIndex之间元素组成的集合(左闭右开)
List<E> subList(int fromIndex,int toIndex);
}
3.常用的子类
- ArrayList
- Vector
- LinkedList
- CopyOnWriteArrayList