Java - Reading from an ArrayList from another class

后端 未结 3 715
梦谈多话
梦谈多话 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:40

    You have an IndexOutOfBoundsException which means that you are trying to access an element in an array which is not existing.

    But in your code posted here you are not accessing an array at all (your for loop will not execute once because the list is empty), which means that your exception is thrown somewhere else.

    But also your code doesn't make any sense. I refactored it for you while staying as close to your code as possible, so you can see how it could work:

    public static void main(String[] args){
        Objects myObjects = new Objects();
        ArrayList listFromMyObjects = myObjects.getList();
        for( int x = 0 ; x < listFromMyObjects.size() ; x++ )
        {
            System.out.println(listFromMyObjects.get(x));
        }
    }
    
    
    public class Objects
    {   
        private ArrayList myList;
    
        public Objects(){
            myList = new ArrayList();
            myList.add(5);
            myList.add(25);
            myList.add(5);
            myList.add(5);
            myList.add(25);
            myList.add(5);
            myList.add(600);
            myList.add(400);
            myList.add(600);
        }
    
        public ArrayList getList(){
            return myList;
        }
    }
    

提交回复
热议问题