我是Java的菜鸟,现在我正在学习泛型。此代码应删除任何大于5的整数。我输入了[10,11,12,1],从理论上讲,我应该只得到[3,4,6,1]。但是我得到了[3,4,6, 11 ,1],我不明白为什么。
public static void main(String args[]) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(4);
list.add(56);
list.add(6);
for (int i = 0; i < 4; i++){
String s = reader.readLine();
list.add(Integer.parseInt(s));
}
for (int i = 0; i < list.size(); i++){
if (list.get(i) > 5)
list.remove(i);
//else
//i++;
}
System.out.println(list);
}
10 11 12 1
[3,4,6,11,1]
答案 0 :(得分:2)
如果您阅读List.remove()
的文档,将会看到索引i
之后的元素向左移动。这意味着在您当前的实现中,每次删除后您都将跳过一个元素,因此,如果两个相邻的元素大于5,则仅其中之一将被删除。
您可以做的是,在使用i--;
删除元素之后,也将当前索引后退一步。您的代码将因此变成
public static void main(String args[]) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(4);
list.add(56);
list.add(6);
for (int i = 0; i < 4; i++){
String s = reader.readLine();
list.add(Integer.parseInt(s));
}
for (int i = 0; i < list.size(); i++){
if (list.get(i) > 5) {
list.remove(i);
i--;
}
}
System.out.println(list);
}
这将输出[3, 4, 1]
,并删除所有大于5的数字。
答案 1 :(得分:2)
答案 2 :(得分:1)
如果您从数组末尾开始检查,则可以正常工作。
public static void main(String args[]) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(4);
list.add(56);
list.add(6);
for (int i = 0; i < 4; i++){
String s = reader.readLine();
list.add(Integer.parseInt(s));
}
for (int i = list.size() - 1; i >=0 ; i--){
if (list.get(i) > 5)
list.remove(i);
}
System.out.println(list);
}
10 11 12 1
[3,4,1]
答案 3 :(得分:0)
我想这是理解如何从列表中删除的练习,但是否则,这是您可以在添加到列表之前进行检查的方式:
public static void main(String args[]) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 4; i++){
System.out.println("type a number: ");
String s = reader.readLine();
int j = Integer.parseInt(s);
if(j < 5) {
list.add(Integer.parseInt(s));
}
}
System.out.println(list);
}