Adding array list to another arraylist

I am trying to add array list in another array list, and returning final array list. I have 4 records in table, when i am trying to display, the first set of record only 4 coming times.

    ArrayList<String> al = new ArrayList<String>();
    ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

    try
    {
        conn=com.sample.DBConnection.getDBConnection();
        String query= null;
        query=com.sample.RRRConstants.REPORT_SUMMERY;
        st = conn.createStatement();
        rs=st.executeQuery(query);
         Map<String, Object[]> summ = new HashMap<String, Object[]>();

        while(rs.next())
        {

            al.add(rs.getString("sched_id"));
            al.add(rs.getString("sched_name"));
            al.add(rs.getString("gen_date"));
            al.add(rs.getString("gen_time"));
            al.add(rs.getString("generated_by"));
            al.add(rs.getString("gen_version"));
            al.add(rs.getString("gen_status"));
            list.add(al);   

        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

Displaying :

     ArrayList<ArrayList<String>> a1 =rs.getSummary();

     ArrayList<String> a2 = new ArrayList<String>();


     for (int i=0 ; i <a1.size() ; ++i)
     {
         a2 = a1.get(i);
         System.out.println(i +" record "+a2.get(0));
         System.out.println(i +" record "+a2.get(1));
         System.out.println(i +" record "+a2.get(2));
         System.out.println(i +" record "+a2.get(3));
         System.out.println(i +" record "+a2.get(4));
         System.out.println(i +" record "+a2.get(5));
         System.out.println(i +" record "+a2.get(6));
     }  
Jon Skeet
people
quotationmark

You're creating a single ArrayList<String>, and adding a reference to that list to your ArrayList<ArrayList<String>> several times.

You need to create a new object within your loop, so that each iteration creates an independent list:

while(rs.next())
{
    ArrayList<String> al = new ArrayList<>();
    ...
}

However, I'd recommend not using ArrayList<String> for this anyway - given that you've got very specific fields, why not create your own type with properties for schedule ID, schedule name etc? That's likely to be a lot easier to work with than a list of strings where you're associating each index with a particular meaning.

people

See more on this question at Stackoverflow