2

I am trying to make it so I can write data to a ArrayList to track random integers and then I will have a previous button that will go back to the last result (This is just testing that code this is not the full code for the project) I am getting an error when trying to take the int arraySize and subtract it by 1 and reprint the data. Any idea why this is happening or how another way to accomplish the task.

int lenth = 10;
ArrayList<Integer> list = new ArrayList<Integer>();
int arraySize = list.size();
Random random = new Random();
int newRandom = random.nextInt(lenth);
list.add(newRandom);
newRandom = random.nextInt(lenth);
list.add(newRandom);
System.out.println(list.get(arraySize));
arraySize--;
System.out.println(list.get(arraySize));

Also here is the error I am getting:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at test.C_MainActivity.main(C_MainActivity.java:22)
2
  • By listArray, do you mean ArrayList? Jun 25, 2015 at 15:52
  • Index start from 0. So, if you have 3 elements, last element will be at index 2 and not at 3. Jun 25, 2015 at 15:53

3 Answers 3

3

When you assign one primitive (such as an int) to another, this copies the value to the new variable. For objects, this works a bit differently in that these variables will point to the same object.

int arraySize = list.size();

So the above line will just set arraySize to the current size of the list, arraySize will not change as the list size changes. Since you do this when the list is empty, it will be and remain 0 and you'll try to get the elements at indices 0 and 0-1 = -1, which is where your exception comes in.

You should just set it after you've inserted all elements instead.


Note that indexing in Java starts at 0, so the last element will already be at list.size() - 1, not list.size().

0
0

You are setting arraySize before anything has been added to the list. The value of arraySize will always be 0 because you only set it at the beginning. When you call arraySize--, arraySize is now -1 and when you call list.get(arraySize), you will get an index out of bound exception as you are asking for index -1.

0

It seems like your goal is to enqueue values in a collection and then dequeue them. A LinkedList, for example, would be more appropriate with its push() and pop() methods.

Anyway you should not keep track of the ArrayList's size through an external variable. Such data is already provided for you inside ArrayList so you just have to query the list to know its size.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.