Kyl*_*e93 1 java class arraylist
我们还没有涵盖ArrayLists只有Arrays和2D数组.我需要做的是能够从另一个类的ArrayList中读取.主要目的是在for循环中读取它们并使用存储在其中的值来显示项目.但是,我已经制作了这个快速程序来测试它并不断收到此错误
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)
Run Code Online (Sandbox Code Playgroud)
这是我的代码
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后是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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人能指出我正确的方向,那将是非常有价值的.我试过调试但是我可以得到任何有用的东西.
提前致谢.
严格地说,例外是由于索引ArrayList0的元素的位置1 .注意你从哪里开始循环索引变量x.但请考虑这一行:
ArrayList <Objects> xcoords = new ArrayList<Objects>();
Run Code Online (Sandbox Code Playgroud)
xcoords指向一个新的,空的ArrayList,而不是您在类对象中创建的那个.为了得到那个 ArrayList,改变方法xco类似
public ArrayList<Integer> xco() { // make sure to parameterize the ArrayList
ArrayList<Integer> xcoords = new ArrayList<Integer>();
// .. add all the elements ..
return xcoords;
}
Run Code Online (Sandbox Code Playgroud)
那么,在你的main方法中
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));
}
}
Run Code Online (Sandbox Code Playgroud)