简体   繁体   中英

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?

First of all, ArrList should not have a starting capital letter (it is not a class but an object).

Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though. You could do something like this

    int ROWS = 10;
    int COLS = 2;
    int [][] matrix = new int[ROWS][];
    for(int i=0; i< matrix.length; i++){
        matrix[i] = new int[COLS];
    }

or, with lists

    int ROWS = 10;
    int COLS = 2;
    List<List<Object>> matrix = new ArrayList<>(ROWS);
    for (int i = 0; i < ROWS; i++) {
        ArrayList<Object> row = new ArrayList<>(COLS);
        for (int j = 0; j < COLS; j++) {
            row.add(new Object());
        }
        matrix.add(row);
    }

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 ie 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.

int[][] arrList=new int[parties.size()][2];
    int i=0,j=0,k=0;
    for(;i<parties.size();i++,j++){
        if(j==1){
            arrList[k][j]=electoralList .get(--i);
            j=-1;
            k++;
        }
        else{
            arrList[k][j]=parties.get(i);
        }
    }
    arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));

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