- 有序集合(也成为序列),该界面的用户可以精确控制列表中每个元素的插入位置。且用户可以通过整数索引(列表中的位置)访问元素,并搜索列表中的元素。与Collection集合不同,列表通常允许重复的元素
- List集合的元素特点是:有序,可重复,元素有索引
- 有序:指的是元素的存储顺序和取出顺序是一致的
- 可重复:指的是List集合可以存储重复的元素
- 元素有索引:指的是List集合中每个元素都是有索引的,且索引是从0开始的
二、成员方法
-
public void add(int index, E element)
- 在集合的指定位置(索引),插入指定的元素,索引越界会报错
-
public E remove(int index)
- 删除指定索引处的元素,并返回被删除的元素,索引越界会报错
-
public E set(int index, E element)
- 修改指定索引处的元素为指定的值,并返回修改前的元素,索引越界会报错
-
public E get(int index)
- 根据索引,获取其对应的元素,索引越界会报错
/** * 定义一个学生类,属性为姓名和年龄 * 创建List集合,用来存储学生对象 * 往List集合中,添加3个学生的信息 * 分别通过两种遍历方式,来遍历List集合 */ public class Test{ public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); list.add(0,new Student("European", 21)); list.add(1,new Student("Sheik", 22)); list.add(2,new Student("欧洲酋长", 23)); for(int i=0;i<list.size();i++){ Student temp = list.get(i); System.out.println("姓名:"+temp.name+",年龄:"+temp.age); } System.out.println("------------------------------------"); int n = 0; while (n<list.size()){ Student temp = list.get(n); System.out.println("姓名:"+temp.name+",年龄:"+temp.age); n+=1; } System.out.println("------------------------------------"); Iterator sIter = list.iterator(); while(sIter.hasNext()){ Student temp = (Student) sIter.next(); System.out.println("姓名:"+temp.name+",年龄:"+temp.age); } } }