0
List<List<String>> lists = new ArrayList();

//fileName is a list of files to iterate through and extract data from

for (int x=0; x<fileName.size(); x++) {

    // CSV Reader object
    CSVReader readFile = new CSVReader(new FileReader(fileName.get(x)));

    String[] nextLine = readFile.readNext(); // Parses through first line with headers

    /**
     * Populates each array with appropriate data
     */
    List<String> tempList = new ArrayList();

    while ((nextLine = readFile.readNext()) != null) {
        tempList.add(nextLine[0]);
    }

    readFile.close();

    lists.add(tempList);

}

My question for this is that I thought array lists were passed by reference. When I run this, I'm basically creating a list of lists, which then is populated for each file I add in. I thought that as soon as this for loop is exited, the "tempList" data would be dereferenced and be open to change in the memory. However, in my tests, the data stays in through a series of calculations without any change. What is the reason for this?

I'm passing an arraylist created in a for loop to another list of lists. Why does this temp list not get thrown into garbage collection when exiting the for loop?

  • 1
    You aren't calling a routine, just a for loop. Also, the value of a List is its' reference. Finally, you shouldn't use a raw-type `ArrayList();` And, `lists` has references to each item from `lists.add(tempList);` – Elliott Frisch Jul 02 '14 at 16:56
  • `lists.add(tempList);` is referencing your list why `GC`? – akash Jul 02 '14 at 16:57
  • 1
    Java is always pass by value. This question is a duplicate of Is Java "pass-by-reference" or "pass-by-value"?, which does a very good job of explaining. – Chris K Jul 02 '14 at 16:58

2 Answers2

0

You're adding a reference to tempList inside your lists.

lists.add(tempList);

Since the object referenced by lists is reachable, each object tempList was referencing is also reachable. They cannot be GC'ed.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

In your lists you store the references to created tempLists. When you exit from the for loop the references stay there. If you wan to release them, so the can be garbage collected. You can call, clear().

List<List<String>> lists = new ArrayList<ArrayList<String>>();

for (int x=0; x<fileName.size(); x++) {
  //populate data to lists
}

//operate on lists data

lists.clear(); // release the references

The GC, can free memory only from objects that does not refer to others.