合并清单项目 [英] combine items of list
本文介绍了合并清单项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个清单,可以说这些项目{30 50 5 60 90 5 80}我想做的是例如将第3个元素和第4个元素结合在一起并得到{30 50 65 90 5 80}
Hi I have a list with lets say these items {30 50 5 60 90 5 80} what I want to do is for example combine the 3rd and 4th element together and have {30 50 65 90 5 80}
你能告诉我我该怎么做吗?我正在使用Java链表类.
Could you tell me how would I do that? I am using the java linked list class.
推荐答案
public class Main {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
list.add(30);
list.add(50);
list.add(5);
list.add(60);
list.add(90);
list.add(5);
list.add(80);
System.out.println(list);
combine(list, 2, 3);
System.out.println(list);
}
public static void combine(List<Integer> list, int indexA, int indexB) {
Integer a = list.get(indexA);
Integer b = list.get(indexB);
list.remove(indexB); // [30, 50, 5, 90, 5, 80]
list.add(indexA, a + b); // [30, 50, 65, 5, 90, 5, 80]
list.remove(indexB); // [30, 50, 65, 90, 5, 80]
}
}
输出为:
[30, 50, 5, 60, 90, 5, 80]
[30, 50, 65, 90, 5, 80]
您需要检查null值,以避免 NullPointerException
You need check nulls values for avoid NullPointerException
这篇关于合并清单项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文