Java String array created inside loop -


i have question regarding differences of following codes:

vector v = new vector(); string [] str_arr = new string[3];  for(int i=0; i<3; i++) {    str_arr[0] = "a";    str_arr[1] = "b";    str_arr[2] = "c";                v.add(str_arr); } system.out.println(v.size());  //answer 3 

versus

vector v = new vector();   for(int i=0; i<3; i++) {    string [] str_arr = new string[3];    str_arr[0] = "a";    str_arr[1] = "b";    str_arr[2] = "c";                v.add(str_arr); } system.out.println(v.size());  //answer 3 

the difference between both codes is, second one, string array created inside loop.

both codes produce same result, want know difference between these two.

the 2 snippets don't produce same result. first snippet adds same array object 3 times vector. second snippet adds 3 different array objects vector.

the results may seem same, since 3 arrays in second snippet contain same values.

if you'd change assignment

str_arr[0] = "a"; str_arr[1] = "b"; str_arr[2] = "c";  

to

str_arr[0] = "a" + i; str_arr[1] = "b" + i; str_arr[2] = "c" + i; 

you'd see in first snippet, arrays in vector contain [a2,b2,c2], since there's 1 array that's getting overwritten.

on other hand, second snippet produce vector contains 3 different arrays - [a0,b0,c0],[a1,b1,c1],[a2,b2,c2].


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -