Ok, remember that everything in Java is a reference. In your example you are storing the reference to strQueryResult in the arraylist. The next thing you do is reassign the values of the array which also modify the reference (it is the same) in the arraylist.
so when you print out the contents of the array list you only see the second set of data. You overwrote the array referenced by the strQueryResult variable. > Subject: [java programming] ArrayList behavior > From: [email protected] > To: [email protected] > Date: Sat, 24 Jan 2009 11:15:12 +0700 > > > 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 > > > > > _________________________________________________________________ Windows Liveā¢: E-mail. Chat. Share. Get more ways to connect. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t2_allup_explore_012009 --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---
