在方法内迭代 ArrayList [英] Iterating ArrayList inside a method

查看:32
本文介绍了在方法内迭代 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 Candidate 对象的 Candidades 类,如下所示:

I have a Candidades class that holds Candidate objects, as follow:

import java.util.*;
public class Candidates<Candidate> extends ArrayList<Candidate>  {

public int getTotalVotesCount()
{
    Iterator it = this.iterator();
    int i, total = 0;

    while(it.hasNext())
    {
        Candidate c = (Candidate)it.next();

        total += c.getVoteCount();
    }
    return total;
}
}

班级候选人如下:

public class Candidate {

private int votes;
private String name;

public String getName()
{
    return this.name;
}

public int getVoteCount()
{
    return this.votes;
}

public void vote()
{
    votes++;
}

public Candidate(String _name)
{
    this.name = _name;
    this.votes = 0;
}
}

我如何迭代它?

我知道迭代代码没问题,因为在课堂外使用代码是可行的.

I know the code for the iteration is ok, as using the code outside the class works.

测试如下:

/**

 * @(#)Test.java
 *
 * Test application
 *
 * @author
 * @version 1.00 2011/3/8
 */
import java.util.*;
public class Test {
public static void main(String[] args) {

    Candidates candidates = new Candidates();

    candidates.add(new Candidate("One"));
    candidates.add(new Candidate("Two"));
    candidates.add(new Candidate("Three"));
    candidates.add(new Candidate("Four"));

    Iterator it = candidates.iterator();

    int i = 0;
    while(it.hasNext())
    {
        i++;

        Candidate c = (Candidate)it.next();

        for(int j = 0; j <= i; j++)
        {
            c.vote();
        }
    }

    int total = 0;
    it = candidates.iterator();
    while(it.hasNext())
    {
        Candidate c = (Candidate)it.next();
        total += c.getVoteCount();
    }

    System.out.printf("Votes: %d", total);
}
}

上面的代码正确打印了 14.

The code above correctly prints 14.

推荐答案

如果你想从类中迭代一个类,那么使用this:

If you are trying to iterate over a class from within the class, then use this:

for (Candidate c : this ) ...

这篇关于在方法内迭代 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆