0

I created an arraylist of LinkedLists in the following manner:

ArrayList<LinkedList<Card>> list = new ArrayList<>(5);

I then needed to add the linkedlists to the arrayList so I did this, which did not seem to work as the ArrayList remained empty

for (position = 0; position < list.size(); position++) {
list.add(new LinkedList<Card>());
}

So then I manually added linkedLists to the arrayList by giving the LinkedLists references:

        LinkedList<Card> temp_list0 = new LinkedList<Card>();
        LinkedList<Card> temp_list1 = new LinkedList<Card>();
        LinkedList<Card> temp_list2 = new LinkedList<Card>();
        LinkedList<Card> temp_list3 = new LinkedList<Card>();
        LinkedList<Card> temp_list4 = new LinkedList<Card>();
        list.add(temp_list0);
        list.add(temp_list1);
        list.add(temp_list2);
        list.add(temp_list3);
        list.add(temp_list4);

Finally, though each iteration, i needed to pull out one of the LinkedLists to add something to it and then put it back where it was in the arraylist but by doing this I lose the reference to the LinkedList and thus the information is lost

for (position = 0; position < deck.length; position++) {
            scan = (deck[position]).getValue();
            temp_list = list.get(scan);
            temp_list.offer(deck[position]);
            list.add(scan, temp_list);
        }

Is there a better way to access to the LinkedLists in the arraylist without losing information, because my way does not work.

1 Answer 1

5

The problem is in your initial for loop; size() returns the number of elements in the list, not the allocated capacity (if the list implementation even has one). Pull out your 5 into a constant and loop from 0 to the constant instead. Then just use get()/set() on the ArrayList normally.

Note that you don't have to "pull out" and "put back" the contained LinkedList objects; you can just call arrayList.get(linkedListNumber).offer(card);.

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

3 Comments

so when I do arrayList.get(linkedListNumber).offer(card); does it know to put it back in the arraylist?
@kimos You need to read up on how Java references work. There is no "putting back" involved; you retrieve the LinkedList and then perform operations on it (such as inserting an object). The LinkedList is still in the ArrayList right where it always was until you tell the ArrayList to replace or remove it.
So the objects LinkedLists created will still be in the array even if I did not give their instances a reference ?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.