0

I am attempting to add arraylists to the arraylist of arraylists I believe(sorry I'm a beginner), but whenever I void the temporary so I can grab the next line of data to be added, it changes the main arraylist as well. Is there any way to copy only the values without making it point to the same reference?

for (int n=0; n!=cellCount+1; n++)
        {
            temp.add(inputFile.nextDouble());
            System.out.println(temp);
        }

        mainList.add(temp);


    //}
temp.clear();
System.out.println(mainList);

prints: [0.0, 4.0, 6.0, 9.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0]As the final temp arraylist before it is cleared

[[]]As the mainList

  • 2
    In the future you should also include in your code snippet the initial definitions of all variables being used (like `temp` in this case). That said, [this question has been answered before](http://stackoverflow.com/a/5785754). – Pierce Darragh Jul 24 '16 at 17:36

1 Answers1

1

I'm assuming temp is your ArrayList.

When you do this:

mainList.add(temp);

you're putting a reference to that array list into mainList. It is not a copy of it, it's a reference to it. You're just reusing the same ArrayList every time.

Instead, create a new ArrayList in each loop (and then you don't need clear), e.g.:

while (/*...whatever, there's clearly some loop here..*/) {
    temp = new ArrayList();
    for (int n=0; n!=cellCount+1; n++)
    {
        temp.add(inputFile.nextDouble());
        System.out.println(temp);
    }

    mainList.add(temp);
}
System.out.println(mainList);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875