运行此代码时输出错误。输出应为
x is added to the set
但我得到这样的输出:
x is added to the set
x is added to the set
x is already added
x is already added
我的代码:
List<Integer> data = new ArrayList<Integer>();
data.add(4);
data.add(1);
int x = 5;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).equals(x)) {
System.out.println("x is already added");
} else {
data.add(x);
System.out.println("x is added to the set");
}
}
答案 0 :(得分:3)
您的数组长度为2.因此循环将运行两次(如果没有其他元素添加到数组中)。
第一次data.get(0)为4,因此将5添加到集合中。现在data.length是3。
x is added to the set
第二次data.get(1)为1,因此将5添加到集合中。现在data.length是4。
x is added to the set
第三次data.get(2)是5
x is already added
第四次(因为data.length是4),data.get(3)是5所以你得到:
x is already added
如果你真的想在将5添加到数组后退出循环,请打破循环:
for (int i = 0; i < data.size(); i++) {
if (data.get(i).equals(x)) {
System.out.println("x is already added");
break;
} else {
data.add(x);
System.out.println("x is added to the set");
}
}
但这种逻辑非常愚蠢。如果您只想添加五个并显示消息,那么您是不是没有循环或其他任何内容直接执行此操作?
答案 1 :(得分:0)
使用for
循环,您可以这样做:
boolean alreadyAdded = false;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).equals(x)) {
alreadyAdded = true;
break;
}
}
if (!alreadyAdded) {
data.add(x);
}
<强>更新强>:
由于您正在使用List
,因此更好的方法是
if (!data.contains(x)) {
data.add(x);
}