I try to get a reference to an element of an ArrayList but I fail.
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?
You can’t do this in Java. All you’re doing is fetching the value from the
ArrayList. That value is a reference, but it’s a reference in Java terminology, which isn’t quite the same as in C++.That reference value is copied to
s1, which is thereafter completely independent of the value in theArrayList. When you change the value ofs1to refer to a new string in this line:that doesn’t change the value in the
ArrayListat all.Now if you were using a mutable type such as
StringBuilder, you could use:Here you’re not changing the value in the
ArrayList– which is still just a reference – but you’re changing the data within the object that the value refers to.