Hi Patrick,

On 24 Jan., 05:15, Patrick_Stiady <[email protected]> wrote:
> 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";

Here you overwrite the array for which you stored a reference in the
first arlQueryResult.add() call.
>                 arlQueryResult.add(strQueryResult);
Here the reference is added for a second time in the list.

>
>                 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?

You can, but before reusing the variable you have to allocate and
assign a new array.

> 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?
As said before, for every turn in the loop you have to allocate a new
array and assign
the new values.
HTH
Ewald

--~--~---------~--~----~------------~-------~--~----~
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