首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java - IndexOutOfBoundsException

Java - IndexOutOfBoundsException
EN

Stack Overflow用户
提问于 2013-09-25 00:46:20
回答 1查看 137关注 0票数 0

我不是Java的初学者,但我也不是专家,这就是为什么我张贴这个帮助/解释。我在互联网上找过很多地方,但我还没有找到答案。

代码语言:javascript
复制
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时,这与此有关。任何帮助都会很棒的!

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-25 00:48:53

在这个代码中

代码语言:javascript
复制
theData.add(tempArray);
tempArray.clear();

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18994424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档