[英]Filling 2d array
Okay probably it's a very easy solution, but I can't seem to find it. 好的,这可能是一个非常简单的解决方案,但我似乎找不到。 I've got two ArrayLists:
我有两个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: 现在,我想制作一个二维int数组,表示像这样的政党和候选人:
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. 我想我已经有合适的for循环来填充数组,但是我只想念正确的公式即可。
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? for循环确实正确吗? 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). 首先,
ArrList
不应以大写字母开头(它不是类,而是对象)。
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. 第二点(我觉得麻烦的是)您没有初始化矩阵,并且partys.size()始终为0。我不确定,因为代码不足。 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. 我将尝试从我如何理解您在这里的需求中回答问题。
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 一个2D数组由一个嵌套数组组成,即ArrList [2] [3] = [[1,2,3],[1,2,3]] ->第一个数字声明作为元素的数组个数,第二个数字声明数组元素的大小或(如果喜欢)长度
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.