3

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?

1
  • a Java reference is like a C pointer. If you change the value of a reference, you just make it point to somewhere else. Commented Dec 26, 2011 at 18:24

2 Answers 2

5

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 the ArrayList. When you change the value of s1 to refer to a new string in this line:

s1 += "modificated";

that doesn't change the value in the ArrayList at all.

Now if you were using a mutable type such as StringBuilder, you could use:

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

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.

Sign up to request clarification or add additional context in comments.

Comments

2

What you are probably looking for is a mutable String, which doesn't come with Java AFAIK, you'll have to create a wrapper class

class MutableString {
  private String value;
  public void setValue(String val){value = val;}
  public String getValue(){return value;}
  public String append(String val){value+=val;//Or use a StringBuilder}
}

Then you can have an ArrayList of MutableString (instead of String), and store references to specific elements of the list (and be able to change them). Of course you won't be able to use (or override) the default operators because they only work with String (so no +=).

You might also want to just use StringBuilder instead of String, but that's not what it's made for.

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.