2 Replies Latest reply: Sep 22, 2013 4:57 PM by rp0428 RSS

    list.clear() outside of <List> finalList = new ArrayList(); will delete element in finalList?

    KonradZuse

      Hello all!

       


      I am using 3 ArrayLists.

       


      the first is List<String>

      the second is List<String[]>

      and the third is a list of those lists List<List>

       

      I use the first list to get the string I need, but I use the second for String.split.

       

      I then need to keep a list of these to use, so I need the third List.
      After adding the second list to the list of lists I want to clear it so I can set up the next list to be added, but if I do list.clear(); it will delete everything in that list.

       

      If I do not clear it, it is fine.

       

      At first I wasn't sure if it was my fault, because I'm not sure if I ever had to do that before, so I made a test case that yields the result if I change the element outside.

       

       

      /*
      * To change this template, choose Tools | Templates
      * and open the template in the editor.
      */
      package javaapplication1;
      
      
      import java.sql.SQLException;
      import java.util.ArrayList;
      import java.util.List;
      
      
      /**
      *
      * @author Konrad
      */
      public class JavaApplication1 {
      
      
          /**
           * @param args the command line arguments
           */
          String a;
          List<String> j = new ArrayList<>();
         
          public JavaApplication1()
          {
              a();
          }
          public void a()
          {
              a = "ADASDSADSA";
              j.add(a);
              a = null;
              System.out.println(j);
          }
          public static void main(String[] args) throws SQLException {
         
              JavaApplication1 a = new JavaApplication1();
             
             
          }
         
      }
      
      

       

      If I change a = null to a = ""; it still yields the original a = "ADASD......";

       

       

       

       

       

       

       

       

       

       

          protected List<String> list = new ArrayList<>();
          protected List<String[]> list2 = new ArrayList<>();
          protected List<List> finalList = new ArrayList<>();
      
      
      
      
      ........
      
      
      
        finalList.add(list2);
                       //list2.clear();
      
      
      
      
      

       

       

      With this I yield an empty array element, even though my array elements exist.  I tried using multiple lists and I just had multiple empty elements.

       

       

      So again I'm not sure if I did something wrong, or is this a bug?  Since my test case worked, I'm confused.

       

      Thanks!

       

      ~KZ