通过以下代码,我期望四个元素,但只得到三个。显然我正在做一些疯狂愚蠢的事情。
import java.util.HashSet;
import java.util.Set;
public class MyTest {
public static void main(String[] args) {
String[] myStrings = new String[] { "a", "b" };
Set<String> set = new HashSet<String>();
for (String x : myStrings) {
for (String y : myStrings) {
String temp = x;
x = y;
y = temp;
set.add(x + y);
}
}
System.out.println(set);
}
}
结果:
[ba, aa, ab]
最佳答案
集合不允许重复,并且您要添加“ba”两次。如果您的循环控制令人困惑,但这是简化的跟踪,并扩展了右值。
x = "a"
y = "a"
temp = "a"
x = "a"
y = "a"
add("aa")
y = "b"
temp = "a"
x = "b"
y = "a"
add("ba")
x = "b"
y = "a"
temp = "b"
x = "a"
y = "b"
add("ab")
y = "b"
temp = "a"
x = "b"
y = "a"
add("ba")
关于java - 交换变量时奇怪的 java for-each 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446185/