13.3.1 List接口的定义
List是Collection的子接口,其中可以保存各个重复的内容。此接口的定义如下:
public interface List<E> extends Collection<E>
但是与Collection不同的是,在List接口中大量地扩充了Collection接口,拥有了比Collection接口中更多的方法定义,其中有些方法还比较常用。表 13-3 列出了List中对Collection接口的扩展方法。
表13-3 List接口的扩展方法
序号 | 方 法 | 类型 | 描 述 |
1 | public void add(int index, E element) | 普通 | 在指定位置增加元素 |
2 | public boolean addAll(int index, Collection<? extends | 普通 | 在指定位置增加一组元素 |
3 | E get(int index) | 普通 | 返回指定位置的元素 |
4 | public int indexOf(Object o) | 普通 | 查找指定元素的位置 |
5 | public int lastIndexOf(Object o) | 普通 | 从后向前查找指定元素的位置 |
6 | public ListIterator<E> listIterator() | 普通 | 为ListIterator接口实例化 |
7 | public E remove(int index) | 普通 | 按指定的位置删除元素 |
8 | public List<E> subList (int fromIndex, int toIndex) | 普通 | 取出集合中的子集合 |
9 | public E set(int index, E element) | 普通 | 替换指定位置的元素 |
List接口比Collection接口扩充了更多的方法,而且这些方法操作起来很方便。但是如果要想使用此接口,则需要通过其子类进行实例化。
13.3.2 List接口的常用子类(1)
1.新的子类:ArrayList
ArrayList是List子类,可以直接通过对象的多态性为List接口实例化。此类的定义如下:
- public class ArrayList<E> extends AbstractList<E>
- implements List<E>, RandomAccess, Cloneable, Serializable
从定义中可以发现ArrayList类继承了AbstractList类。AbstractList类的定义如下:
- public abstract class AbstractList<E>
- extends AbstractCollection<E> implements List<E>
此类实现了List接口,所以可以直接使用ArrayList为List接口实例化。下面通过一些实例操作为读者讲解List接口中主要方法的使用。
(1)实例操作一:向集合中增加元素
要想完成此类操作,可以直接使用Collection接口中定义的两个方法。
增加一个元素:public boolean add(E o)。
增加一组元素:public boolean addAll(Collection<? extends E> c)。
也可以使用List扩充的add()方法在指定位置处增加元素。
在指定位置处添加元素:public void add(int index,E element)。
范例:验证增加数据的操作
- package org.lxh.demo13.listdemo;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- public class ArrayListDemo01 {
- public static void main(String[] args) {
- List<String> allList = null ;
// 定义List对象- Collection<String> allCollection = null ;
// 定义Collection对象- allList = new ArrayList<String>();
- // 实例化List对象,只能是
- String类型
- allCollection = new ArrayList<String>();
- // 实例化Collection,只能
- 是String类型
- allList.add("Hello");
- // 从Collection继承的方法
- allList.add(0, "World");
// 此方法为List扩充的方法- System.out.println(allList);
// 输出集合中的内容- allCollection.add("LXH");
// 增加数据- allCollection.add("www.mldn.cn");
// 增加数据- allList.addAll(allCollection);
// 从Collection继承的方- 法,增加一组对象
- allList.addAll(0, allCollection);
// 此方法是List自定义的,- 增加一组对象
- System.out.println(allList);
- // 输出对象,调用
- toString()方法
- }
- }
程序运行结果:
- [World, Hello]
- [LXH, www.mldn.cn, World, Hello, MLDN, www.mldn.cn]
从程序的运行结果中可以发现,使用List中的add(int index,E element)方法可以在集合中的指定位置增加元素,而其他的两个add()方法只是在集合的最后进行内容的追加。