开发者

How to change a string in Set<String> during foreach iteration?

开发者 https://www.devze.com 2023-03-07 01:14 出处:网络
I have a set of strings that I\'d like to iterate over, and change all of those who equal something, to equal s开发者_如何学Pythonomething else:

I have a set of strings that I'd like to iterate over, and change all of those who equal something, to equal s开发者_如何学Pythonomething else:

// Set<String> strings = new HashSet()
for (String str : strings) {
  if (str.equals("foo")) {
    // how do I change str to equal "bar"?
  }
}

I've tried replace() which didn't work. I've also tried removing "str" and adding the desired string, which caused an error. How would I go about doing this?


Two points:

  1. String is immutable; you can't "change" a String. You can remove one from the Set and replace it with another, but that's all that changing.
  2. A Set means "only one copy of each". What's the "change all" stuff? Why do you have to iterate over the Set? Why won't this do it?

    strings.remove("foo");
    strings.add("bar");


Since Set can't have duplicates, what you are trying to do is a bit strange. Why iterate?

if (strings.contains("foo")) {
  strings.remove("foo");
  strings.add("bar");
}

Make sure that whole block is synchronized properly if that strings set is shared between threads.


You should not change the set while iterationg over it.

Better try this:

Set<String> strings = new HashSet();
strings.add("foo");
strings.add("baz");

Set<String> stringsNew = new HashSet();

for (String str : strings) {
    if (str.equals("foo")) {
    stringsNew.add("bar");
    } else {
    stringsNew.add(str);
    }
}

System.out.println(stringsNew);


If you change your HashSet in the middle of iteration, you get ConcurrentModificationException. That means, you have to remove "foo" first, and then add "bar" - outside iterator


A set is a collection that contains no duplicate objects. Therefore if you wish to 'replace' an object in a set with something else, you can simply remove it first, and then add the string you wish to 'replace' it with.


// Set<String> s = new HashSet();

     for (String str : s) {
                if (str.equals("foo")) {
                    s.remove(str);
                    s.add("bar");
                }
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消