Java 中的 2d ArrayList 添加数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1771565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
2d ArrayList in Java adding data
提问by Sizemj
I need little help on a homework assignment. I have to create a 10 by 10 ArrayList, not an array. This is what I have and I just need a hint on how to do a for loop to add the date to the 2D ArrayList. By the way this is for putting data that are grades; going from 100 to 82. (Yes I know it is homework but need to be pointed in the correct direction)
我在家庭作业上几乎不需要帮助。我必须创建一个 10 x 10 ArrayList,而不是一个数组。这就是我所拥有的,我只需要一个关于如何执行 for 循环以将日期添加到 2D 的提示ArrayList。顺便说一下,这是用于放置成绩数据;从 100 到 82。(是的,我知道这是作业,但需要指出正确的方向)
public void q6()
{
//part a
ArrayList<ArrayList<Double>> grades;
//part b
grades = new ArrayList<ArrayList<Double>>(10);
//second dimension
grades.add(new ArrayList<Double>(10));
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
// grades.get().add(); Not sure what to do here?
// If this was an array I would do something like:
// grades[i][j] = 100 -j -i;
}
}
}
回答by Rickard
Something like this could do?
这样的事情可以吗?
public void q6()
{
//part a
ArrayList<ArrayList<Double>> grades;
//part b
grades = new ArrayList<ArrayList<Double>>(10);
//second dimension
for(int i = 0; i < 10; i++)
{
List<Double> current = new ArrayList<Double>(10);
grades.add(current);
for(int j = 0; j < 10; j++)
{
current.add(100 - j - i);
}
}
}
回答by Mykola Golubyev
Given the code, all you left to do is change it a little to receive 10x10 matrix.
给定代码,您剩下要做的就是稍微改变它以接收 10x10 矩阵。
public class Main
{
public static final int ROW_COUNT = 5;
public static final int COL_COUNT = 10;
public static void main(String[] args)
{
ArrayList<ArrayList<Double>> grades = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < ROW_COUNT; i++)
{
ArrayList<Double> row = new ArrayList<Double>();
for (int j = 0; j < COL_COUNT; j++)
{
row.add(100.0 - j - i);
}
grades.add(row);
}
for (int i = 0; i < ROW_COUNT; i++)
{
for (int j = 0; j < COL_COUNT; j++)
{
System.out.print(grades.get(i).get(j));
System.out.print(", ");
}
System.out.println("");
}
}
}

