How to change a string in Set <String> during foreach iteration?
I have a set of lines that I would like to iterate over, and change all those who equal something to something else:
// Set<String> strings = new HashSet()
for (String str : strings) {
if (str.equals("foo")) {
// how do I change str to equal "bar"?
}
}
I tried replace () which did not work. I also tried removing the βstrβ and adding the desired line, which caused an error. How can i do this?
+3
6 answers
Two points:
- The string is immutable; you cannot βchangeβ the line. You can remove it from the set and replace it with another, but everything changes.
A set means "only one copy of each." What is "change everything"? Why do you have to sort out a set? Why won't it be?
strings.remove ("Foo");
strings.add ("bar");
+6