本文介绍了添加ArrayList的连续元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力实现以下目标:
I am trying to achieve the following:
因此,此列表:{146,153,151,150}将被转换为146,例如146 + 7 = 153、153 +(-2)= 151,依此类推.我写了以下内容:
So this list: {146,153,151,150} would be transformed into 146 as 146+7=153, 153+(-2)=151 and so on.I wrote the following:
List<Integer> list = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
list2.add(0, list.get(0));
for(int i=0;i<list.size()-1;i++)
{
list2.add(i+1, list.get(i+1)+list.get(i));
System.out.println(list2);
}
但是,这将返回{146,153,6,-3}.我在做什么错了?
However, this is returning {146,153,6,-3}. What I am doing wrong?
推荐答案
您应该添加到list2.get(i)
而不是list.get(i)
List<Integer> list = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
list2.add(0, list.get(0));
for(int i=0;i<list.size()-1;i++)
{
list2.add(i+1, list.get(i+1)+list2.get(i));
System.out.println(list2);
}
这篇关于添加ArrayList的连续元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!