【问题标题】:Java - IndexOutOfBoundsExceptionJava - IndexOutOfBoundsException
【发布时间】:2013-09-30 10:12:50
【问题描述】:

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

当我清除我曾经添加到theDatatempArray 时,我感觉这与此有关。任何帮助都会很棒!

谢谢

【问题讨论】:

    标签: java eclipse arraylist indexoutofboundsexception


    【解决方案1】:

    在这段代码中

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

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

    【讨论】:

    • 谢谢!我犯的愚蠢错误。我这样做的唯一原因是因为我是为一个类似的 C++ 项目这样做的(它允许你这样做)。
    • @CraiGreen 不客气。花几分钟阅读Is Java pass-by-reference。另外,如果它涵盖了所有内容,请考虑接受答案。
    • 我做到了 - 只需等待几分钟,StackOverflow 就会让我这样做。
    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 2016-03-22
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2012-08-15
    • 1970-01-01
    相关资源
    最近更新 更多