Create new List<String>() by getting member of List<List<String>>() without linking them

I am trying to initialize a List<String>listBuffer that is equal to a member of a List<List<String>>listOfLists, without linking them. Every time I add to “listBuffer”, it automatically adds to that member of the “listOfLists”. How do I create a “listBuffer” that is not linked to “listOfLists”?
//Initial Problem

    List<List<String>>listOfLists = new ArrayList<List<String>>();
    listOfLists.add(new ArrayList<String>());
    List<String>listBuffer = listOfLists.get(0);
    List<String>listBuffer2 = listBuffer;//2ndBufferAttempt
    listBuffer.add("anyString");
    listBuffer2.add("anyString2");
    System.out.println(listOfLists.get(0));
    //Output is [anyString,anyString2]

    //Simple Solution(Not sure whether its the best way)
    List<List<String>>listOfLists = new ArrayList<List<String>>();
    listOfLists.add(new ArrayList<String>());
    List<String>listBuffer = new ArrayList<String>();
    listBuffer.addAll(listOfLists.get(0));
    listBuffer.add("anyString");
    System.out.println(listOfLists.get(0));
//Output is "[]"

I expected the output to be “[]”.
The output is instead “[anyString,anyString2]”.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Edit: Parameter list of java.util.Collections.copy() corrected

The = does not create a new instance of what type ever, but simply copies a pointer. In your code, listOfLists.get(0), listBuffer, and listBuffer2 point to the same memory area, and so it is not surprising that those are linked together. If you don’t want them being linked, don’t link them. I’s that simple.

List<String>listBuffer;
List<String>listBuffer2;
Collections.copy(listBuffer, listOfLists.get(0));
Collections.copy(listBuffer2, listBuffer);//2ndBufferAttempt

creates new, independent, unlinked lists; that should do the job.

Jason
Guest

Where ever you’re getting base from is linked to listOfLists in some way. Perhaps you could show your base declaration for more clarity.

Edit: if you want your other list to be separate, instead of getting it from somewhere else, do something like:

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