An ArrayList
is not an array. In an array, when you create it, you say how many places you need, and then you can access all of them. If you said:
int[] arr = new int[10];
Then you can use arr[5]
and arr[8]
etc. Immediately.
But an ArrayList
is not like that. It only has as many items as you add to it. The number that you pass to the constructor just tells it how many places you think you may need, but it's not the number of items available in the list - the initial size is 0. After you add
an item, the size is 1, and so on. So you don't actually have to pass a number when you create the list:
List a = new ArrayList(); // The size is 0 but you can add items.
List b = new ArrayList(10); // The size is also 0! The 10 is just the capacity!
The set
method changes an existing item. If you didn't add an item, then it won't work - it complains that you are trying to change an item that doesn't exist. So first, you need to use add
to add items to the list, and then you can change them with set
.
If you need to reverse a list, you can use Collections.reverse(list)
. It will reverse the given list. If you want to have one straight list and one reverse list, you can do:
// Fill list 1 by adding to it, then:
List list2 = new ArrayList(list1);
Collections.reverse(list2);
This will first copy all the items from list1
to list2
, then reverse list2
.