问题描述
我们还没有覆盖的ArrayList只是数组和二维数组。我需要做的是能够从另一个类的ArrayList阅读。的主要目的是从他们在一个读循环,并使用在其中存储的值来显示的项目。不过,我已经这个快速程序来对其进行测试,并保持收到此错误
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)
下面是我的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));
}
}
}
和则该类所在的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.
先谢谢了。
推荐答案
严格地说,异常是由于一个的ArrayList
0元素的索引位置1。请注意,你开始你循环变量 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
,而不是你在课堂上的对象创建的。要获得的是的的ArrayList
,改变方法 XCO
像
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;
}
那么,在你的主
法
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));
}
}
这篇关于爪哇 - 从一个ArrayList从另一个类阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!