How to pull data moving backwards in a java ArrayList -


i trying make can write data arraylist track random integers , have previous button go last result (this testing code not full code project) getting error when trying take int arraysize , subtract 1 , reprint data. idea why happening or how way accomplish 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 error getting:

exception in thread "main" java.lang.arrayindexoutofboundsexception: -1 @ java.util.arraylist.elementdata(unknown source) @ java.util.arraylist.get(unknown source) @ test.c_mainactivity.main(c_mainactivity.java:22) 

when assign 1 primitive (such int) another, copies value new variable. objects, works bit differently in these variables point same object.

int arraysize = list.size(); 

so above line set arraysize current size of list, arraysize not change list size changes. since when list empty, , remain 0 , you'll try elements @ indices 0 , 0-1 = -1, exception comes in.

you should set after you've inserted elements instead.


note indexing in java starts @ 0, last element @ list.size() - 1, not list.size().


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -