0

I was having issues adding my ArrayList items to a linked list. It was working perfectly fine at first but for some reason, doesn't want to act right now I transferred the information to my computer.

Basically, what is happening is that instead of 2 items from my array list being moved to my linked list, 4 items move (the two items copying themselves).

Here's my code:

for(Customer obj : customers){

        remaining.addAll(obj.getIndex(), customers);
        System.out.println(remaining);
        //System.out.println(obj.getIndex() + " Customer: " + obj.getType());
    }

My output for that: [Slow Customer 0, Slow Customer 1] [Slow Customer 0, Slow Customer 0, Slow Customer 1, Slow Customer 1]

I understand why I'm getting two lists BUT my main question to you all is why am I getting the second output.

******Disclaimer: when I printed the remaining on the outside, I only got the second list.*******

2
  • 2
    Because for every customer in the list, you add all the customers to the linked list, instead of just adding the customer itself. Why not just ditch that loop and just use remaining.addAll(customers)? Commented May 2, 2017 at 17:04
  • @JBNizet thanks a lot. It worked! Commented May 2, 2017 at 18:30

1 Answer 1

1

I think you misunderstood the method addAll(int index, Collection collection) What the method does: it takes every element of the consumed collection and adds those elements to the list that the method is called on. They will be added at the specified index and all following elements will be shifted.(for further info see the java documentation https://docs.oracle.com/javase/7/docs/api/java/util/List.html#addAll(int,%20java.util.Collection )
However you are calling it just so many times and thus adding so many objects because you put it in a loop ;)

Use remaining.addAll(customers); only once and ditch the loop.

(Or keep the loop and use add(obj); on each object instead)

EDIT: corrected explanation of addAll method

Sign up to request clarification or add additional context in comments.

1 Comment

@JBNizet i fixed my mistake - explanation should now be correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.