我只是写了这个函数来添加值到多维数组列表,但不明白为什么所有的增加值覆盖到最近的增加值。我得弄清楚为什么会这样。正如javadoc所说,它必须这样做"将指定的元素附加到该列表的末尾"。我在他的代码中没有看到任何地方,以前的附加价值可以被覆盖。还有一件奇怪的事情是数组的大小会增加
下面是我的输出:
[0.4, 0.42, 0.4, 1.2200000000000002, 0.0010000000000000009] after add 0
[0.4, 0.42, 0.4, 1.2200000000000002, 0.0010000000000000009] after add 1
[0.4, 0.42, 0.4, 1.2200000000000002, 0.0010000000000000009] after add 2
[0.4, 0.42, 0.4, 1.2200000000000002, 0.0010000000000000009] after add 3
[0.4, 0.42, 0.4, 1.2200000000000002, 0.0010000000000000009] after add 4
[0.4, 0.42, 0.42, 1.24, 0.01200000000000001] after add 0
[0.4, 0.42, 0.42, 1.24, 0.01200000000000001] after add 1
[0.4, 0.42, 0.42, 1.24, 0.01200000000000001] after add 2
[0.4, 0.42, 0.42, 1.24, 0.01200000000000001] after add 3
[0.4, 0.42, 0.42, 1.24, 0.01200000000000001] after add 4
[0.4, 0.42, 0.42, 1.24, 0.01200000000000001] after add 5
[0.4, 0.44, 0.4, 1.2400000000000002, 0.011999999999999983] after add 0
[0.4, 0.44, 0.4, 1.2400000000000002, 0.011999999999999983] after add 1
[0.4, 0.44, 0.4, 1.2400000000000002, 0.011999999999999983] after add 2
[0.4, 0.44, 0.4, 1.2400000000000002, 0.011999999999999983] after add 3
[0.4, 0.44, 0.4, 1.2400000000000002, 0.011999999999999983] after add 4
[0.4, 0.44, 0.4, 1.2400000000000002, 0.011999999999999983] after add 5
[0.4, 0.44, 0.4, 1.2400000000000002, 0.011999999999999983] after add 6
下面是我的函数:
public void createArrayList(ArrayList<Double> list,ArrayList<Double>
listLaid,int size,double sum, double absValue){
ArrayList<Double> workArray = new ArrayList<>();
ArrayList<ArrayList<Double>>
workMatrix= new ArrayList<>();
double abs=0;
for(int a = 0; a < size ;a++){
for(int b = 0; b < size ; b++){
for (int c = 0 ; c < size; c++){
abs =Math.abs(sum - list.get(a) - list.get(b) - list.get(c));
if( abs <= absValue){
double totalSum = listLaid.get(a) + listLaid.get(b) +
listLaid.get(c);
workArray.clear();
workArray.add(listLaid.get(a));
workArray.add(listLaid.get(b));
workArray.add(listLaid.get(c));
workArray.add(totalSum);
workArray.add(abs);
workMatrix.add(workArray);
}
}
}
}
}
for (int i = 0; i < workMatrix.size(); i++)
System.out.println(darbineMat.get(i)+" after add "+i);
您总是在列表中添加相同的实例。这意味着最终workMatrix
的所有行都相同。
您必须为每个新行创建一个新的ArrayList
。替换
workArray.clear();
workArray = new ArrayList<Double>();
应该足够了。
EDIT:"引用"的概念乍一看可能会令人困惑(在某些编程语言中,这个概念并不以同样的方式存在)。但是当你创建一个像这样的列表实例时
ArrayList<Double> workArray = new ArrayList<Double>();
那么workArray
只是对您正在创建的实例的引用。你可以把它想象成一个"句柄"(事实上,它更像是C/c++中的一个"指针",但这现在可能变得太混乱了)。关键是当你写
ArrayList<ArrayList<Double>> workMatrix = new ArrayList<>();
ArrayList<Double> workArray = new ArrayList<>();
workMatrix.add(workArray);
则只将引用添加到workMatrix
列表中。这个引用仍然指向您创建的唯一实例:
// This prints "true": The first element of the matrix
// and the workArray are IDENTICAL. (Not only equal,
// but really IDENTICAL)
System.out.println(workMatrix.get(0) == workArray);