Java - Reading from an ArrayList from another class -


we've not covered arraylists arrays , 2d arrays. need able read arraylist class. main aim read them in loop , use values stored in them display items. however, have made quick program test out , keep getting error

java.lang.indexoutofboundsexception: index: 0, size: 0     @ java.util.arraylist.rangecheck(arraylist.java:604)     @ java.util.arraylist.get(arraylist.java:382)     @ main.main(main.java:14) 

here code

import java.util.arraylist;  public class main {     public static void main()     {         system.out.println("test");         arraylist <objects> xcoords = new arraylist<objects>();          for( int x = 1 ; x < xcoords.size() ; x++ )         {             system.out.println(xcoords.get(x));         }     } } 

and class arraylist

import java.util.arraylist;  public class objects {     public void xco()     {         arraylist xcoords = new arraylist();         //x coords         //destroyable         xcoords.add(5);         xcoords.add(25);         xcoords.add(5);         xcoords.add(5);         xcoords.add(25);         xcoords.add(5);         //static walls         xcoords.add(600);         xcoords.add(400);         xcoords.add(600);     } } 

if can point me in correct direction valuable. i've tried debug can helpful.

thanks in advance.

strictly speaking, exception due indexing location 1 of arraylist 0 elements. notice start loop index variable x. consider line:

arraylist <objects> xcoords = new arraylist<objects>(); 

xcoords points new, empty arraylist, not 1 created in class objects. that arraylist, change method xco like

public arraylist<integer> xco() { // make sure parameterize arraylist     arraylist<integer> xcoords = new arraylist<integer>();      // .. add elements ..      return xcoords; } 

then, in main method

public static void main(string [] args) { // add correct arguments      //..     arraylist <integer> xcoords = (new objects()).xco();      for( int x = 0 ; x < xcoords.size() ; x++ ) { // start index 0         system.out.println(xcoords.get(x));     } } 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -