Java – reference to ArrayList element

I tried to get a reference to the ArrayList element, but I failed

ArrayList<String> test = new ArrayList<String>();

test.add("zero");
test.add("one");
test.add("two");

 String s1 = test.get(1);
 String s2 = test.get(1);

 System.out.println(test.get(1) +" " + s1 + " " + s2);

 s1 += " modificated";

 System.out.println(test.get(1) +" " + s1 + " " + s2);

Any suggestions?

Solution

You can't do this in Java All you have to do is get the value from ArrayList This value is a reference, but it is a reference in Java terminology, which is not exactly the same as the reference in C

The reference value is copied to S1 and then completely independent of the value in ArrayList When you change the value of S1 to refer to the new string in this line:

s1 += "modificated";

This does not change the value in ArrayList at all

Now, if you use a variable type like StringBuilder, you can use:

StringBuilder builder = list.get(0);
builder.append("more text");
System.out.println(list.get(0)); // Would include "more text"

Here, you won't change the value in the ArrayList - it's still just a reference - but you're changing the data in the object referenced by the value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>