在这篇文章中,我们将看到 Java 中的 Iterator 和 ListIterator 之间的区别。它们都用于遍历,但最好指出它们之间的差异。
1.Country.java
package org.arpit.java2blog; 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; } }
2.IterateListMain.java
package org.arpit.java2blog; 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 india=new Country("India",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(india); 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 : India Japan France Russia ----------------------------- Iterating using ListIterator in forward direction : India Japan France Russia ----------------------------- Iterating using ListIterator in backward direction : Russia France Japan India
原文链接:https://codingdict.com/