Java - 从另一个类的 ArrayList 读取 [英] Java - Reading from an ArrayList from another class

查看:32
本文介绍了Java - 从另一个类的 ArrayList 读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们没有只讨论 ArrayLists 和 2D 数组.我需要做的是能够从另一个类的 ArrayList 中读取.主要目的是在 for 循环中读取它们并使用存储在其中的值来显示项目.但是,我已经制作了这个快速程序来测试它并不断收到此错误

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 for loop and use the values stored in them to display items. However, I have made this quick program to test it out and keep getting this error

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.get(ArrayList.java:382)
    at Main.Main(Main.java:14)

这是我的代码

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));
        }
    }
}

然后是ArrayList所在的类

And then the class where the ArrayList is

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 someone can point me in the correct direction it would be so valuable. I've tried to debug however I can get anything helpful.

提前致谢.

推荐答案

严格来说,异常是由于索引位置 1 的 ArrayList 有 0 个元素.注意循环索引变量 x 的起点.但请考虑这一行:

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 <Objects> xcoords = new ArrayList<Objects>();

xcoords 指向一个新的、空的 ArrayList,而不是您在类 Objects 中创建的那个.要获得那个 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<Integer> xco() { // make sure to parameterize the ArrayList
    ArrayList<Integer> xcoords = new ArrayList<Integer>();

    // .. add all the elements ..

    return xcoords;
}

然后,在你的 main 方法中

then, in your 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 from index 0
        System.out.println(xcoords.get(x));
    }
}

这篇关于Java - 从另一个类的 ArrayList 读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆