Hello All,

I have been playing around with ArrayList and encounter this kind of
behavior:

import java.util.ArrayList;

public class TestArrayList1 {
        static ArrayList<String[]> arlQueryResult = new
ArrayList<String[]>(10);
        static String[] strQueryResult = new String[4];
        static String[] strQueryResult2 = new String[4];

        public static void main(String[] args) {
                strQueryResult[0] = "a";
                strQueryResult[1] = "b";
                strQueryResult[2] = "c";
                strQueryResult[3] = "d";
                arlQueryResult.add(strQueryResult);

                strQueryResult[0] = "e";
                strQueryResult[1] = "f";
                strQueryResult[2] = "g";
                strQueryResult[3] = "h";
                arlQueryResult.add(strQueryResult);
                
                for (int i = 0; i< arlQueryResult.size(); i++){
                        for (int j = 0; j<=3; j++){
                                String str = arlQueryResult.get(i)[j];
                                System.out.println("Result " + i + j + ": " + 
str);
                        }
                }
        
        }
                
}


The output is not "a b c d e f g h" as expected but:
Result 00: e
Result 01: f
Result 02: g
Result 03: h
Result 10: e
Result 11: f
Result 12: g
Result 13: h

I have to use the array of strQueryResult2 to store "e f g h" and 
arlQueryResult.add(strQueryResult2); to obtain this output:
Result 00: a
Result 01: b
Result 02: c
Result 03: d
Result 10: e
Result 11: f
Result 12: g
Result 13: h

Thus, the questions are:
1. Why can't I reuse the array of strQueryResult to add a new element in
the ArrayList of arlQueryResult?
2. What is the best practice to add a new element of Array in ArrayList
in this case, if I want to put the algorithm in a loop and perform the
arlQueryResult.add(...) many times as the content of the array of
strQueryResult varies?


Thanks for the advice,
Patrick



--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to