【Java類集】_ListIterator介面筆記(執行個體親測)

來源:互聯網
上載者:User

【Java類集】_ListIterator介面筆記

本章目標:
掌握ListIterator與Iterator介面的關係及區別
掌握ListIterator介面的使用限制

3、具體內容

ListIterator介面
Iterator介面的主要功能是由前向後單向輸出,而此時如果想實現由後向前或者是由前向後的雙向輸出,則就必須使用Iterator的子介面————ListIterator。

LisIterator介面定義如下:
public interface ListIterator<E> extends Iterator<E>
雖然此介面可以進行雙向的輸出,但是遺憾的是Collection介面中並沒有定義可以為此類執行個體化的操作,只有List 介面中才存在了ListIterator介面的執行個體化操作

範例:完成雙向輸出

import java.util.ArrayList;import java.util.List;import java.util.ListIterator;public class ListIteratorDemo01{    public static void main(String[] args){        List<String> all = new ArrayList<String>();        all.add("hello");        all.add("_");        all.add("world!!!");        ListIterator<String> iter = all.listIterator();        System.out.println("由前向後輸出");        while(iter.hasNext()){            String str = iter.next();            System.out.print(str+"、");        }            System.out.println("\n由後向前輸出");        while(iter.hasPrevious()){            String str = iter.previous();            System.out.print(str+"、");        }        }}

輸出:
由前向後輸出
hello、_、world!!!、
由後向前輸出
world!!!、_、hello、

此時,已經完成了雙向的輸出操作。
但是,在使用此操作的時候一定要注意一點:一定要先進行由前向後輸出,之後才能進行由後向前的輸出。
使用ListIterator還可以進行增加及替換元素
add()
set()

import java.util.ArrayList;import java.util.List;import java.util.ListIterator;public class ListIteratorDemo01{    public static void main(String[] args){        List<String> all = new ArrayList<String>();        all.add("hello");        all.add("_");        all.add("world!!!");        ListIterator<String> iter = all.listIterator();        System.out.println("由前向後輸出");        while(iter.hasNext()){            String str = iter.next();            System.out.print(str+"、");            iter.set("LI-"+str);        }            System.out.println("\n由後向前輸出");        iter.add("LXH");        while(iter.hasPrevious()){            String str = iter.previous();            System.out.print(str+"、");        }        }}

輸出:

由前向後輸出
hello、_、world!!!、
由後向前輸出
LXH、LI-world!!!、LI-_、LI-hello、

總結:
1.如果要想使用ListIteral只能依靠List介面完成。
2.如果要進行由後向前的輸出,則只能先進行由前向後的輸出。
3.對於此介面中的增加及修改操作瞭解即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.