简体   繁体   中英

Java String array created inside loop

I have a question regarding the differences of the 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 only difference between both codes is, for the second one, string array is created inside the loop.

Both the codes produce same result, but i want to know what is the difference between these two.

The two snippets don't produce the same result. The first snippet adds the same array object 3 times to the Vector. The second snippet adds three different array objects to the Vector.

The results may seem the same, since all three arrays in the second snippet contain the same values.

If you'd change the assignment from

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 that in the first snippet, the all the arrays in the Vector contain [A2,B2,C2] , since there's just one array that's getting overwritten.

On the other hand, the second snippet would produce a Vector that contains three different arrays - [A0,B0,C0] , [A1,B1,C1] , [A2,B2,C2] .

In the second version, the String[] goes out of scope at the end of each iteration. This means that you can't access it elsewhere. After the loop, the variable no longer exists. You also don't keep the value between iterations.

EDIT : The array itself still exists, as the vector keeps a strong reference to it.

However, there are some redundancy issues in your code.

for(int i=0; i<3; i++)
{
   str_arr[0] = "A"; //all
   str_arr[1] = "B"; //of this
   str_arr[2] = "C"; //is redundant  
   v.add(str_arr);
}

Here (first version), you assign the same values to the array each iteration even though the variable still exists from one iteration to another, so you don't need most of the body

Though the output will be the same, the state of your application will be different at the last line of both programs.

On the first, your heap will have only one array of Strings, and on the second it will have three.

第一个代码段比第二个代码段快一点(不占用内存和进程),因为它只实现一次数组并在每个循环中更新其值,但是在第二个代码段中,它实现了新数组并在每个循环中为其注册一个地址

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM