我不是 Java 初学者,但也不是专家,这就是我发布此文章以寻求帮助/解释的原因。我在互联网上查找了很多地方,但没有找到我正在寻找的答案。
public class Driver {
public static ArrayList<ArrayList<Integer>> theData; // ArrayList to store the ArrayList of values
final static int dataSize = 20; // length of the line of data in the inFile
/***
* Read in the data from the inFile. Store the current line of values
* in a temporary arraylist, then add that arraylist to theData, then
* finally clear the temporary arraylist, and go to the next line of
* data.
*
* @param inFile
*/
public static void getData(Scanner inFile) {
ArrayList<Integer> tempArray = new ArrayList<Integer>();
int tempInt = 0;
while (inFile.hasNext()) {
for (int i = 0; i < dataSize; i++) {
tempInt = inFile.nextInt();
tempArray.add(tempInt);
}
theData.add(tempArray);
tempArray.clear();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner inFile = null;
theData = new ArrayList<ArrayList<Integer>>();
System.out.println("BEGIN EXECUTION");
try {
inFile = new Scanner(new File("zin.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
getData(inFile);
}
System.out.println(theData.get(5).get(5)); // IndexOutOfBoundsException here
System.out.println("END EXECUTION");
}
}
我在标记它的地方得到一个 IndexOutOfBoundsException 。这里有趣的是,当我试图弄清楚这一点时,我测试了方法 getData
是否正常工作,因此该方法在 getData< 中的 while 循环中迭代
我打印出了数组的大小-theData
,以及数组theData
中数组的大小,你知道吗,它返回了正确的大小和值(value)。因此,基本上,当调用 getData
时,它可以正常工作并存储值,但是当我尝试调用 Main
中的值时,ArrayList 中没有值。
我有一种感觉,这与我清除用于添加到 theData
的 tempArray
有关。任何帮助都会很棒!
谢谢
最佳答案
在此代码中
theData.add(tempArray);
tempArray.clear();
变量tempArray
是对ArrayList
对象的引用。您将该引用添加到 theData
ArrayList
。当您对其调用 clear()
时,您将清除其引用传递给 theData
的同一个对象。无需调用 clear()
,只需初始化一个新的 ArrayList
。
关于Java - IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994424/