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

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

问题描述

我保存的候选对象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;
}
}

我如何遍历呢?

我知道code的迭代是确定的,作为使用code类作品之外。

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

在code以上正确打印14。

The code above correctly prints 14.

推荐答案

如果你正试图从类中迭代一个类,然后使用这个

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

for (Candidate c : this ) ...

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

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