我不是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中数组的大小,您知道的是,它返回了一个正确的大小和值。因此,基本上当调用getData时,它正确工作并存储值,但是当我试图调用Main中的值时,ArrayList中没有值。
我有一种感觉,当我清除我曾经添加到tempArray中的theData时,这与此有关。任何帮助都会很棒的!
谢谢
发布于 2013-09-25 00:48:53
在这个代码中
theData.add(tempArray);
tempArray.clear();变量tempArray是对ArrayList对象的引用。将该引用添加到theData ArrayList。在它上调用clear()时,您正在清除传递给theData的引用的同一个对象。而不是调用clear(),只需初始化一个新的ArrayList。
https://stackoverflow.com/questions/18994424
复制相似问题