Search code examples
javaarraysfor-loopmultidimensional-arraynested-loops

Filling 2d array


Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:

ArrayList<Candidate>partyList and ArrayList<Party>electoralList 

Now I want to make a 2d int array that represents the parties and candidates like this:

p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3 
etc.

I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.

int[][]ArrList;
for (int i=0; i<parties.size(); i++){ 
        for(int j=0; j<parties.get(i).getPartyList().size(); j++){
            ArrList[i][j]=

Is the for-loop indeed correct? And what is the formula to fill the array then?


Solution

  • I will try and answer the question from how I understood what you are looking for here.

    • You should understand this first:
    • A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements

    • If you are looking for to represent the candidates and parties as numbers. Here is my solution:

      int[][]ArrList = new int[parties.size()][electoral.size()]
      for (int depth=0; depth < parties.size(); depth++){ 
          for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
              ArrList[depth][itemIndex]= itemIndex;
      

    I hope this is what you were looking for.