Java二维数组ArrayList

时间:2016-02-10 12:13:04

标签: java arrays arraylist

对于学校,我必须根据荷兰投票系统进行投票计划,其中有候选人参加。对于这个课程,我做了一个班级"候选人"它有候选人姓名的getter和setter。然后是一个班级" Party"其中包含:

ArrayList<Candidate>CandidateList 

以及按名称添加候选人的方法。接下来,我创建了一个&#34; PartyList&#34;其中包含:

ArrayList<Party>Parties 

和这个方法:

public void addParty(Party party){
    Parties.add(new Party());

我认为这样做会更好:

ArrayList<ArrayList<Party>>Parties

但我的老师说这就足以制作一个一维的ArrayList。现在到了我迷路的部分:

我有另一个班级&#34;投票&#34;进行最后的投票,但为此我必须制作一个二维的候选人和候选人,如下所示:

1 1
1 2
1 3
2 1
2 2
3 1
etc.

其中第一列代表派对,第二列代表候选人。我知道第一列可以使用Parties.size(),但第二列不可能这样,因为CandidateList有多个Arraylists。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

class Poll {
private Integer label;
private Integer value;

// Constructor or setter
public void Poll(Integer label, Integer value) {
    if (label == null || value == null) {
        return;
    }
    this.label = label;
    this.value = value;
}

// getters

public Integer getLabel() {
    return this.label;
}

public Integer getValue() {
    return this.value;
}

}

像这样使用它来存储2个项目而不是多维的东西

private ArrayList<Poll> items = new ArrayList<Poll>();
items.add(new Stuff(label, value));
 for (Poll item: items) {
 doSomething(item.getLabel()); // returns Integer      
 doSomething(item.getValue()); // returns Integer
 }
相关问题