Java – 从另一个类的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) 

这是我的代码

 import java.util.ArrayList; public class Main { public static void Main() { System.out.println("Test"); ArrayList  xcoords = new ArrayList(); for( int x = 1 ; x < xcoords.size() ; x++ ) { System.out.println(xcoords.get(x)); } } } 

然后是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); } } 

如果有人能指出我正确的方向,那将是非常有价值的。 我试过调试但是我可以得到任何有用的东西。

提前致谢。

严格地说,exception是由于索引具有0个元素的ArrayList位置1。 注意你从哪里开始循环索引变量x 。 但请考虑这一行:

 ArrayList  xcoords = new ArrayList(); 

xcoords指向一个新的空ArrayList ,而不是您在类Objects中创建的那个。 要获取 ArrayList ,请更改xco方法

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

然后,在你的main方法

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

在这里,您只需创建两个完全不相关的列表。 要么数组列表是Objects类的属性,要么通过实例方法检索它,要么从实例或静态方法返回它,要么使属性为静态。 IMO前两个在大多数情况下都是可取的。

 public class Objects { public static List getXcoords() { List xcoords = new ArrayList(); // Your same code, but adding: return xoords; } } 

然后使用它:

 import java.util.ArrayList; public class Main { // Note the lower-case "main" here. You want that. public static void main() { List xcoords = Objects.getXcoords(); // etc. 

此外,您的List应该是Integer ,而不是Objects ,它将创建一个包含Objects实例的集合。 你可能想退后一步,以更好的方式将列表与数组联系起来 – 你不会创建一个Objects数组,对吗? 不,你有一个intInteger数组。

还有,有Arrays.asList

您有一个IndexOutOfBoundsException ,这意味着您正在尝试访问不存在的数组中的元素。

但是在这里发布的代码中你根本没有访问数组(因为列表是空的,你的for循环不会执行一次),这意味着你的exception会被抛出到其他地方。

但是你的代码也没有任何意义。 我在尽可能接近您的代码的同时为您重构了它,因此您可以看到它是如何工作的:

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