简体   繁体   中英

Java two dimensional Array of ArrayList

For school I have to make a voting program according to the Dutch voting system where there are parties which have candidates. For this program I have made a class "Candidate" which has a getter and setter for the name of the candidate. Then there is a class "Party" which contains:

ArrayList<Candidate>CandidateList 

and a method to add candidates by name. Next, I made a class "PartyList" which contains:

ArrayList<Party>Parties 

and this method:

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

I thought it would be better to do it like this:

ArrayList<ArrayList<Party>>Parties

but my teacher said it would be enough to make a one dimensional ArrayList. Now comes the part where I get lost:

I have another class "Voting" in which the final voting takes place, but for that i have to make a two-dimensional array of the parties and candidates that will look like this:

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

In which the first column represents the party and the second represents the candidate. I know that the first column would be possible by using Parties.size() but the second column wouldn't be possible this way because there are more than one Arraylists of CandidateList. How can i accomplish this?

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

}

use it like this to store 2 items rather than multidimensional stuff

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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM