【发布时间】:2012-02-25 17:11:02
【问题描述】:
我正在尝试使用下面的代码来创建多维 ArrayList。我的代码很好地填充了内部 ArrayList(localSolutions),但是当我尝试将该 ArrayList 添加到外部 ArrayList(解决方案)时,出现问题,它会添加空 ArrayLists。
public class MathCapstone {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> list = entireList(10);
for(int q = 0;q<list.size();q++) {
System.out.println(list.get(q));
}
public static ArrayList<ArrayList<Integer>> entireList(int max) {
ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> localSolutions = new ArrayList<Integer>();
for(int i = 1; i <= max; i++) {
for(int j = 1; j < i; j++) {
//System.out.println(j + "mod" + i + "=" + (j*j)%i);
if ((j*j)%i == 1) {
localSolutions.add(j);
}
}
//System.out.println(localSolutions.toString());
solutions.add(localSolutions);
localSolutions.clear();
}
return solutions;
}
最后一点:使用 ArrayLists 的 HashMap 会更好吗(最终我将创建 CDF 的最大值约为 10k)?
【问题讨论】:
-
如果您要使用的索引都是介于 0 和某个值之间的数字,则使用
HashMap<Integer, Whatever>与ArrayList<Whatever>相比没有任何好处,并且您会损失一点性能。如果您需要非整数键,或者索引的分布很稀疏,则 HashMap 会更好。 -
也可以考虑
List<List<Integer>> solutions = new ArrayList<List<Integer>>()。 -
@aclear16 我拒绝了您对我的回答的编辑,因为我所做的是故意的,并且是修复的一部分。请不要在没有充分理由(例如测试代码更改)的情况下更改其他用户答案的语义——如果您认为自己发现了一个错误,最好在不确定时添加评论。
标签: java multidimensional-array arraylist