Java - IndexOutOfBoundsException

标签 java eclipse arraylist indexoutofboundsexception

我不是 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 中没有值。

我有一种感觉,这与我清除用于添加到 theDatatempArray 有关。任何帮助都会很棒!

谢谢

最佳答案

在此代码中

theData.add(tempArray);
tempArray.clear();

变量tempArray是对ArrayList对象的引用。您将该引用添加到 theData ArrayList。当您对其调用 clear() 时,您将清除其引用传递给 theData 的同一个对象。无需调用 clear(),只需初始化一个新的 ArrayList

关于Java - IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994424/

相关文章:

java - 将文件上传到服务器保存的文件包含无效字符

java - HTTP 状态 404 Apache Tomcat 错误 Spring MVC Java?

java - 似乎无法让 Reegex 匹配

java - setOnclicklistener 方法不起作用

java - Eclipse Java 缺少所需的源文件夹 : 'src'

java - 将未知泛型类型与 List 类一起使用

java - 从 ArrayList<ArrayList<Object>> 到固定大小的数组/列表

java - 如何让 REST 服务为 Java 8 (Local|Offset)DateTime 生成一个简单的字符串(使用 Swagger 时)?

java - 全局对象的成员变量也应该设为全局吗?

Java JCreator List 引用 ArrayList 不起作用?