Java - Reading from an ArrayList from another class

后端 未结 3 712
梦谈多话
梦谈多话 2020-12-20 06:00

We\'ve not covered ArrayLists only Arrays and 2D arrays. What I need to do is be able to read from an ArrayList from another class. The main aim is to read from them in a fo

3条回答
  •  心在旅途
    2020-12-20 06:32

    Strictly speaking, the exception is due to indexing location 1 of an ArrayList with 0 elements. Notice where you start you for loop index variable x. But consider this line:

    ArrayList  xcoords = new ArrayList();
    

    xcoords points to a new, empty ArrayList, not the one you created in class Objects. To get that ArrayList, change the method xco like

    public ArrayList xco() { // make sure to parameterize the ArrayList
        ArrayList xcoords = new ArrayList();
    
        // .. add all the elements ..
    
        return xcoords;
    }
    

    then, in your main method

    public static void main(String [] args) { // add correct arguments
    
        //..
        ArrayList  xcoords = (new Objects()).xco();
    
        for( int x = 0 ; x < xcoords.size() ; x++ ) { // start from index 0
            System.out.println(xcoords.get(x));
        }
    }
    

提交回复
热议问题