gpt4 book ai didi

java - 在方法中迭代 ArrayList

转载 作者:行者123 更新时间:2023-12-03 08:28:40 27 4
gpt4 key购买 nike

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

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

类(class)候选人如下:

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

我如何遍历它?

我知道迭代代码没问题,因为在类外部使用代码是可行的。

测试如下:

/**

* @(#)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。

最佳答案

如果您尝试从类内部迭代一个类,请使用this:

for (Candidate c : this ) ...

关于java - 在方法中迭代 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5236112/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com