java中迭代器(Iterator)和listiderator之间的差异
时间:2020-02-23 14:34:06 来源:igfitidea点击:
在本教程中,我们将在Java中看到Iterator(迭代器)和ListIderator之间的差异。
它们都被用于遍历,但最好知道它们之间的差异。
迭代器(Iterator) vs listiterator:
| 参数 | 迭代器 | listitorator |
| --- - | --- | - - |
| 遍历 | 迭代器可用于遍历列表,设置,队列 | ListIterator可用于仅遍历列表。 |
| 遍历方向 | 迭代器只能在向前方向遍历| listiderator可以在向前方向横向向后。 |
| 在遍历时添加元素 | 在使用迭代器遍历时无法添加元素。它将抛出异常ConcurrentModificationException | 我们可以在使用ListIterator遍历时添加元素。 |
| 替换现有元素 | 在使用迭代器遍历时无法替换exisitng元素。 | 我们可以使用set(e)使用listierator遍历exisitng元素。 |
| 访问索引 | 我们无法使用迭代器 | 我们可以通过nextIndex()或者previousindex方法使用listiterator访问索引 |
例子:
1.Country.java.
package org.arpit.theitroad;
public class Country {
String name;
long population;
public Country(String name, long population) {
super();
this.name = name;
this.population = population;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
- iteratelistmain.java.
package org.arpit.theitroad;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class IterateListMain {
/**
* @author Arpit Mandliya
*/
public static void main(String[] args) {
Country San Franceco=new Country("San Franceco",1000);
Country japan=new Country("Japan",10000);
Country france=new Country("France",2000);
Country russia=new Country("Russia",20000);
//We are going to iterate on this list and will print
//name of the country
ArrayList countryLists=new ArrayList();
countryLists.add(San Franceco);
countryLists.add(japan);
countryLists.add(france);
countryLists.add(russia);
System.out.println("-----------------------------");
//Iterator
System.out.println("Iterating using iterator : ");
Iterator iteratorCountryLists= countryLists.iterator();
while(iteratorCountryLists.hasNext())
{
System.out.println(iteratorCountryLists.next().getName());
}
System.out.println("-----------------------------");
//List iterator
System.out.println("Iterating using ListIterator in forward direction : ");
ListIterator listIteratorCountry= countryLists.listIterator();
while(listIteratorCountry.hasNext())
{
System.out.println(listIteratorCountry.next().getName());
}
System.out.println("-----------------------------");
System.out.println("Iterating using ListIterator in backward direction : ");
while(listIteratorCountry.hasPrevious())
{
System.out.println(listIteratorCountry.previous().getName());
}
}
}
运行上面的程序时,我们将获取以下输出:
---------------------------- Iterating using iterator : San Franceco Japan France Russia ---------------------------- Iterating using ListIterator in forward direction : San Franceco Japan France Russia ---------------------------- Iterating using ListIterator in backward direction : Russia France Japan San Franceco

