美文网首页
List接口

List接口

作者: 还是那个没头脑 | 来源:发表于2020-08-05 11:01 被阅读0次

    介绍&常用方法

    java.util.List接口 extends Collection接口

    List接口的特点:

            1.有序的集合,存储元素和取出元素的顺序是一致的。
            2.有索引,包含了一些带索引的方法
            3.允许存储重复的元素

    List接口中带索引的方法(特有):

            - public void add(int index, E element):将指定的元素吗,添加到该集合中的指定位置上。
            - public E get (int index):返回集合中指定位置的元素。
            - public E remove(int index):移除列表中指定位置的元素,返回的是被移除的元素。
            - public E set(int index, E element):用指定元素替换集合中指定位置的元素,返回值是更新更新前的元素。
    注意:
            操作索引的时候,一定要防止索引越界异常
            IndexOutOfBoundsException:索引越界异常,集合会报
            ArrayIndexOutOfBoudsException:数组索引越界异常
            StringIndexOutOfBoudsException:字符串索引越界异常

    List集合遍历的三种方式
    // 使用普通的for循环
    for(int i = 0; i < list.size(); i++){
        String s = list.get(i);
         System.out.println(s);
    }
    
    // 使用迭代器
    Iterator<String> it = list.iterator();
    while(it.hasNext()){
        String s = it.next();
         System.out.println(s);
    }
    
    // 使用增强for
    for (String s : list){
        System.out.pringln(s);
    }
    

    List集合子类的特点:

    • ArrayList集合
      底层是数组结构实现,查询快、增删慢
    • LinkedList集合 底层是链表结构实现,查询慢、增删快

    LinkedList集合

    java.util.LinkdList集合 implemets List接口
    LinkedList集合的特点:

    1. 底层是一个链表结构:查询慢,增删快
    2. 里面包含大量操作首尾元素的方法
      注意:使用LinkedList集合特有的方法,不能使用多态
     - public void addFirst(E e):将指定元素插入此列表的开头。
     - public void addLast(E e):将指定元素插入此列表的结尾。
     - public void push(E e):将元素推入此列表所表示的堆栈。
    
     - public E getFirst():返回此列表的第一个元素。
     - public E getLast():返回此列表的最后一个元素。
    
     - public E removeFirst():移除并返回此列表的第一个元素。
     - public E removeLast():移除并返回此列表的最后一个元素。
     - public E pop():从此列表所表示的堆栈处弹出一个元素。
    
     - public boolean isEmpty():如果列表不包含元素,则返回true。
    

    相关文章

      网友评论

          本文标题:List接口

          本文链接:https://www.haomeiwen.com/subject/duzyrktx.html