在方法内迭代ArrayList

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

import java.util.*; public class Candidates extends ArrayList { 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; } } 

我如何迭代它?

我知道迭代的代码是可以的,因为使用类外的代码可以工作。

测试如下:

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

如果您尝试从类中迭代一个类,那么使用:

 for (Candidate c : this ) ... 

没有必要扩展ArrayList (除非你认为这可能更清晰,或者你没有发布的其他内容)。

您可以创建CandidateArrayList并使用foreach迭代:

 List candidates = new ArrayList(); candidates.add(new Candidate("One")); candidates.add(new Candidate("Two")); candidates.add(new Candidate("Three")); candidates.add(new Candidate("Four")); int total = 0; foreach(Candidate c : candidates) { c.vote(); total += c.getVoteCount(); } System.out.printf("Votes: %d", total); 

我会让我的候选人课程像这样:

 public class Candidates() { private List candidates = new ArrayList(); public int getTotalVotesCount() { int total = 0; for (Candidate candidate : candidates) { total += candidate.getVoteCount(); } return total; } } 

你仍然需要填充候选人,但我会建议使用foreach循环。

不要扩展ArrayList ,实现List ,并使用委托 ,添加自己的方法。 如果可以,也可以使用for-each 。

Candidates实际上并不是ArrayList的子类型 – 它不是扩展ArrayListfunction的专用通用容器,它只是一个ArrayList +方便的方法,用于粘贴在那里的特定类型。

我可以为此做什么: Candidate类就像你一样, Candidates类是一个方便API的静态助手类:

 public final class Candidates { private Candidates() {} //singleton enforcer public static int getTotalVotes(Iterable candidates) { //check for nulls int total = 0; for (Candidate c : candidates) total += c.getVoteCount(); return total; } //other convenience methods } 

然后,正如其他人指出的那样,使用您选择的集合,并使用以下代码:

 Collection candidates = new //...whatever // voting scheme int totalvotes = Candidates.getTotalVotes(candidates); 
 public class Candidates extends ArrayList { 

这是一个类型参数名称 = Candidate的列表(它只是一个名称,与Candidate类无关)

 public class Candidates extends ArrayList { 

这是一份候选人名单。

我没有阅读完整的问题和所有的答案,但扩展ArrayList最不可能不是你想要做的。 您更希望使用合成而不是inheritance。