簡體   English   中英

Java二維數組的ArrayList

[英]Java two dimensional Array of ArrayList

對於學校,我必須根據荷蘭的投票系統制定投票計划,那里有有候選人的政黨。 對於這個程序,我制作了一個“候選人”類,其中有一個用於獲取候選人姓名的getter和setter方法。 然后是一個“ Party”類,其中包含:

ArrayList<Candidate>CandidateList 

以及按名稱添加候選人的方法。 接下來,我制作了一個“ PartyList”類,其中包含:

ArrayList<Party>Parties 

和這種方法:

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

我認為最好這樣做:

ArrayList<ArrayList<Party>>Parties

但是我的老師說制作一個一維ArrayList就足夠了。 現在是我迷路的部分:

我還有另一個“投票”類別,在該類別中進行最終投票,但是為此,我必須對當事方和候選人進行二維排列,如下所示:

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

其中第一列代表政黨,第二列代表候選人。 我知道第一列可以通過使用Parties.size()來實現,但是第二列則不能這樣,因為CandidateList的數組列表不止一個。 我怎樣才能做到這一點?

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
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM