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.
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.