Islam Ismayilov Islam Ismayilov - 1 year ago 49
Java Question

how sum of 2 arraylist?

i got below mentioned error when run code:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.LinkedList.checkPositionIndex(Unknown Source)
at java.util.LinkedList.addAll(Unknown Source)
at Collection.Dynamycmaasiv.Collecktionaddlist.main(


public static void main(String[] args) {
LinkedList<Integer> num = new LinkedList<Integer>();
LinkedList<Integer> numodd = new LinkedList<Integer>();
LinkedList<Integer> numeven = new LinkedList<Integer>();
LinkedList<Integer> sumoffevenandodd = new LinkedList<Integer>();// help
// me
// to
// solve

for (double i = 0; i < 50; i++) {
num.add((int) i);
if (i % 2 == 0) {
numeven.add((int) i);
} else {
numodd.add((int) i);



for (int i =0; i<numeven.size(); i++){

sumoffevenandodd.addAll(numeven.get(i)+ numodd.get(i), null);



Answer Source

addAll() is not about adding up numbers. It is about adding all the elements of the method parameter to the collection itself.

So, you need to loop, like

int sum = 0;
for (Integer numberFromList : numeven) {
  sum = sum + numberFromList;

Or, if you have Java8, you can use streams:

int sumEven =;

Sum, done.

And for the record: the real lesson to be learned here: read the javadoc. Don't assume that method called addAll() does what you suppose it does. Turn to the javadoc and inform yourself what reality thinks about your assumptions.

But just to be clear; as I got carried away with your question, too.

In your code, if you change

sumoffevenandodd.addAll(numeven.get(i)+ numodd.get(i), null);


sumoffevenandodd.add(Collections.singletonList(numeven.get(i)+ numodd.get(i)));

it should work, too.

Long story short: if you intended to really have a list with 50 sums within, then my first paragraphs do not really help with your problem. But it isn't exactly clear what you wanted to do; so I leave my answer as is - to address both possible explanations what is "wrong" in your logic.