第四章 如何在java中迭代列表


在这篇文章中,我们将看到如何在 java 中迭代列表。有四种迭代列表的方法。

  • 循环
  • 对于每个循环(Java 5)
  • While 循环
  • 迭代器

下面的示例将帮助您了解如何在 java 中迭代列表。我正在使用自定义对象列表以更好地理解

1.国家.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;

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);

        // For loop
        System.out.println("Iterating using for loop : ");
        for (int i = 0; i < countryLists.size(); i++) {
            Country countryObj=countryLists.get(i);
            System.out.println(countryObj.getName());
        }
        System.out.println("-----------------------------");

        // For each loop
        System.out.println("Iterating using for each loop : ");
        for (Country countryObj:countryLists) {
            System.out.println(countryObj.getName());
        }
        System.out.println("-----------------------------");

        // While loop
        System.out.println("Iterating using while loop : ");
        int i=0;
        while(i<countryLists.size())
        {
            Country countryObj=countryLists.get(i);
            System.out.println(countryObj.getName());
            i++;
        }

        System.out.println("-----------------------------");

        // Iterator
        System.out.println("Iterating using iterator : ");
        Iterator iteratorCountryLists= countryLists.iterator();
        while(iteratorCountryLists.hasNext())
        {
            System.out.println(iteratorCountryLists.next().getName());
        }

    }
}

运行它,您将得到以下输出:

Iterating using for loop : 
India
Japan
France
Russia
-----------------------------
Iterating using for each loop : 
India
Japan
France
Russia
-----------------------------
Iterating using while loop : 
India
Japan
France
Russia
-----------------------------
Iterating using iterator : 
India
Japan
France
Russia


原文链接:https://codingdict.com/