Reputation:
I'm not a beginner at Java, but nor am I an expert, which is why I am posting this for help/explanation. I've looked in many places across the internet, and there hasn't been an answer I'm looking for.
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");
}
}
I get an IndexOutOfBoundsException where I label it at. The interesting thing here is that when I was trying to figure this out, I tested to see if the method getData
was working correctly, so as the method was iterating in the while loop in getData
I printed out the size of the array-theData
, AND the size of the arrays in the array theData
, and what do you know, it returned a correct size and value. So basically when getData
is called on, it works correctly and stores the values, but when I try to call on the values in Main
, There is no values in the ArrayList.
I have a feeling this has something to do with when I clear the tempArray
I used to add to theData
. Any help will be great!
Thanks
Upvotes: 0
Views: 144
Reputation: 280011
In this code
theData.add(tempArray);
tempArray.clear();
the variable tempArray
is a reference to an ArrayList
object. You add that reference to the theData
ArrayList
. When you call clear()
on it, you're clearing the same object whose reference you passed to theData
. Instead of calling clear()
just initialize a new ArrayList
.
Upvotes: 4