我有两个包含以下内容的列表:
Result List: null
List2: { 1, 2, 3, 4, 5, 6, 7, etc.}
结果列表是:
Result List: { 1, 2, 3, 4, 5, 6, 7, etc.}
List2: { 2, 1, 3, 4, 6, 2, 1, etc.}
然后Result List
是:
Result List: { 3, 3, 6, 8, 11, 8, 8, etc.}
如您所见,列表只是逐个元素添加。
我试图通过它实现它:
ArrayList<Double> tempList = new ArrayList<Double>();
for (int l = 0; l < entries.length; l++) {
double result = resultList.get(l) + valueList.get(l);
tempList.add(result);
if(resultlist == null) {
resultList = templist;
}
}
然而,这似乎在java中不起作用。
感谢您的回答!
答案 0 :(得分:2)
由于错误,您的结果位于tempList
而不是resultlist
!
检查resultlist
null
是否有意义。
double result = resultList.get(l) + valueList.get(l); // resultList is not null
tempList.add(result);
if(resultlist == null) { // this is not needed, this is always not null
resultList = templist; // never executed
}
public static void main(String[] args) throws IOException {
List<Long> resultlist = Arrays.asList(0L, 0L, 0L, 0L, 0L, 0L);
calculateList(resultlist, Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L));
calculateList(resultlist, Arrays.asList(2L, 1L, 3L, 4L, 6L, 2L));
System.out.println(Arrays.toString(resultlist.toArray()));
}
private static void calculateList(List<Long> resultList, List<Long> input) {
for (int i = 0; i < resultList.size(); i++) {
resultList.set(i, resultList.get(i) + input.get(i));
}
}
结果
[3, 3, 6, 8, 11, 8]
答案 1 :(得分:-3)
最好从空列表开始而不是空值。我认为你的代码会这样工作
你可以使用这样的东西
if(resultList == null)
{
resultList = new ArrayList<Double>();
}
ArrayList<Double> tempList = new ArrayList<Double>();
for (int l = 0; l < entries.length; l++) {
double result = valueList.get(l);
if(resultList.size()>l)
{
result += resultList.get(l);
}
tempList.add(result);
if(resultlist == null) {
resultList = templist;
}
}