一篇文章帶你了解ListIterator接口
后臺回復“Java”即可獲贈Java學習資料
一、ListIterator接口
(一)我們之前學過了Iterator對象迭代器,它提供了hasNext()方法是判斷集合中是否存在下一個遍歷元素,如果還有元素沒被遍歷,返回true;反之,返回false。還有一個next()方法是返回集合中的下一個元素,這兩個方法都可以實現(xiàn)集合元素的迭代。ListIterator迭代器是Iterator子類,它在父類的基礎(chǔ)上添加了一些方法。
(二)ListIterator方法如下所示:
1.void add(Object o)方法:把指定的元素插入到列表中。
2.boolean hasPrevious()方法:若是以反向遍歷列表,列表有多個元素,則返回true。
3.Object previous()方法:返回列表中上一個元素。
4.void remove()方法:在列表中刪除由next()方法或previous()方法返回的最后一個元素。
二、ListIterator接口void add(Object o)方法、boolean hasPrevious()方法
(一)void add(Object o)方法把指定的元素插入到列表中。
(二)boolean hasPrevious()方法若是以反向遍歷列表,列表有多個元素,則返回true。
(三)例子的實現(xiàn):
import java.util.ArrayList;import java.util.ListIterator;public class t4 {public static void main(String[] args) {// TODO Auto-generated method stubArrayList al=new ArrayList();al.add("a");al.add("b");al.add("c");System.out.println(al);//獲取ListIterator對象ListIterator it =al.listIterator(al.size());//判斷這個對象有沒有前一個元素while(it.hasPrevious()){System.out.println(it.hasPrevious());if(it.hasPrevious()==true){break;}}}}
運行結(jié)果是:

三、ListIterator接口Object previous()方法、void remove()方法
(一)Object previous()方法返回列表中上一個元素。
(二)void remove()方法:在列表中刪除由next()方法或previous()方法返回的最后一個元素。
(三)例子的實現(xiàn):
import java.util.ArrayList;import java.util.ListIterator;public class t4 {public static void main(String[] args) {// TODO Auto-generated method stubArrayList al=new ArrayList();al.add("a");al.add("b");al.add("c");al.add("d");al.add("e");System.out.println("集合中所有元素:"+al);//獲取ListIterator對象ListIterator it =al.listIterator(al.size());//判斷這個對象有沒有前一個元素while(it.hasPrevious()){Object o=it.previous();//對象的上一個元素//獲取打印對象的元素System.out.print(o+"\t");//remove()方法if(o.equals("c")){it.remove();}}System.out.println("\n刪除某個元素后集合所有元素:"+al);}}
運行的結(jié)果是:

四、 經(jīng)典算法題
1.一個球從100米高度自由落下,每次落地后反彈回原來高度的一半后,球再落下來。寫一個程序計算球在第n次落地后,總共經(jīng)過了多少米?當n=10,經(jīng)過的米數(shù)。
代碼的實現(xiàn):
public class t8 {public static void main(String[] args) {// TODO Auto-generated method stubdouble high=100;double sum=100;for(int i=2;i<=10;i++){high=high/2;sum+=2*high;}System.out.println("n=10,經(jīng)過的米數(shù)為:"+sum);}}
運行的結(jié)果是:

五、總結(jié)
本文主要介紹了ListIterator接口、ListIterator接口void add(Object o)方法、boolean hasPrevious()方法、ListIterator接口Object previous()方法、void remove()方法,還有一個經(jīng)典算法。介紹了ListIterator接口的方法通過例子幫助理解。希望大家通過本文的學習,對你有所幫助!
------------------- End -------------------
往期精彩文章推薦:

歡迎大家點贊,留言,轉(zhuǎn)發(fā),轉(zhuǎn)載,感謝大家的相伴與支持
想加入Java學習群請在后臺回復【入群】
萬水千山總是情,點個【在看】行不行
