List接口、列表迭代器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013317445/article/details/81951587

List集合的特点

有序(存储顺序和取出顺序一致),可重复。
List接口继承自Collection接口。

遍历List集合

练习:
List集合存储字符串并遍历
List集合存储学生对象并遍历
根据上一节Collection的练习,很容易写出来。
List还有一个特有遍历方法:size()和get()结合。

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class BianliList {
    public static void main(String[] args){
        //创建集合对象
        List l= new ArrayList();

        //给集合添加元素
        l.add("just");
        l.add("a");
        l.add("sec");

        //遍历集合之使用迭代器
        Iterator it= l.iterator();
        while(it.hasNext()){
            //System.out.print(it.next()+" ");//just a sec
            String s= (String)it.next();
            System.out.print(s+" ");  //just a sec
        }


        //遍历集合之使用List的size()方法和get()方法
        for(int index=0; index< l.size(); index++){
            System.out.print(l.get(index)+" ");//just a sec
        }
    }
}

List特有的一些功能(比起上一层的Collection)

因为有序,所以它的索引更有意义。从而它比起Collection会有一些特有功能。

  • 添加:
    public void add(int index, E element):指定位置添加指定的元素 public
    boolean addAll(int index, Collection c):指定位置添加指定的集合

  • 删除:
    public E remove(int index):移除此列表指定位置的元素
    boolean remove(Object o) :移除指定元素在此列表中的第一个出现(如果存在)

  • 获取:
    E get(int index):返回列表中指定位置的元素
    int indexOf(Object o):返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。
    int lastIndexOf(Object o):返回此列表中最后出现的指定元素的索引;如果列表不包含此元素,则返回 -1。
    List subList(int fromIndex, int toIndex) :返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图。

  • 修改:
    E set(int index, E element): 用指定元素替换列表中指定位置的元素

  • 列表迭代器:
    ListIterator listIterator()
    ListIterator迭代器继承自Iterator迭代器

列表迭代器ListIterator

ListIterator迭代器继承了Iterator迭代器,所以可以直接使用Iterator的hasNext()和Next()方法。
它多了个逆向遍历,它必须先正向遍历,才能逆向遍历,所以一般意义不大,不使用。
提供了boolean hasPrevious()和E previous()方法,实现逆向遍历。

ListIterator接口还提供了一些方法:
void add(E e) :将指定的元素插入列表 ,在刚才迭代的元素后面添加。
void remove() :从列表中删除由 next()或 previous()返回的最后一个元素)。
void set(E e) :用 指定的元素替换由 next()或 previous()返回的最后一个元素。
这些方法的存在说明我们可以使用列表迭代器去修改元素。

猜你喜欢

转载自blog.csdn.net/u013317445/article/details/81951587
今日推荐