1

I'm iterating through an ArrayList, modifying the string, and trying to add it to a new list. It doesn't change the original list. Within a foreach loop in Java, is it creating a copy of the object so I can add it?

List<String> newString = new ArrayList<String>(); 
for (String s : lineOfWords {  // lineOfWords is a String that has text in it
   s = s.replaceAll("\\b(\\w+)\\b(\\s+\\1)+\\b", "$1"); 
   newString.add(s); 
}  

Thanks in advance!

EDIT: I don't mean for it to change the original string, but to add the new string, in this case s, to my newString ArrayList.

2
  • It's not supposed to change the original list. Did you want that? Commented Aug 6, 2010 at 15:44
  • Your comment says lineOfWords was a String? Shouldn't it be a ArrayList<String>, according to your description? Commented Aug 6, 2010 at 15:45

5 Answers 5

3

Yes, Strings are immutable. So with the call to...

s = s.replaceAll("\\b(\\w+)\\b(\\s+\\1)+\\b", "$1"); 

after this line executes, s is an entirely new String, not the one you started with.

Update I hope lineOfWords is an array of String objects? Not "a String that has text in it."

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

Comments

1

Yes, you are creating a new String object each time you call s.replaceAll. You are then assigning that new String object to the temporary variable s, which has no effect on any strings that you have previously added to the List or on any strings in the original List.

Comments

0

You original list is unchanged.

Your "s" variable is local to the loop, on entry to the body loop it refers to the string in the original list, but then the s.replace() is returning a reference to a new String.

Comments

0

Yes as String is immuatable any operation on it that modifies it actually creates a copy of it and in your loop assigning it to 's' will not change the original contents of the list.

Comments

0

You are creating a new string object when you perform the replace operation - as strings in Java are immutable.

You can see for yourself when objects are actually the same or not using the "==" operator, which compares references when used on objects. Since String is an object it has this reference comparison behaviour, but it is sometimes confused due to java interning strings to that in many cases two equal strings of characters actually refer to the same object.

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.