Linked Questions

Popular Questions

Delete numbers larger than x in an ArrayList

Asked by At

I'm a noob in java and right now I'm learning about generics. This code should delete any integer larger than five. I typed [10, 11, 12, 1], in theory, I should only get [3, 4, 6, 1]. But I'm getting [3, 4, 6, 11, 1], I don't understand why..?

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]

Related Questions