1

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]

Mr.Java
  • 25
  • 6
  • Why should `[10, 11, 12, 1]` output `[3, 4, 6, 1]`? And your code doesn't have `[10, 11, 12, 1]` anyway. – RaminS Feb 11 '19 at 20:13
  • @Gendarme The list is prepopulated with 3,4,56,6 and then user input is added, which is where the 10,11,12,1 comes from. – azurefrog Feb 11 '19 at 20:14
  • Oh, I see that now. – RaminS Feb 11 '19 at 20:15
  • 1
    @OP, if the code is supposed to delete numbers higher than 5, how can the expected output include a 6? – azurefrog Feb 11 '19 at 20:15
  • This is not a particularly Java question. In Java, you would need to filter your list by condition `element <= x` using stream API: `mylist.stream().filter(i -> i <=x).collect(Collectors.toList())` – scrutari Feb 11 '19 at 20:15
  • Possible duplicate of [Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – tsolakp Feb 11 '19 at 20:16
  • @tsolakp The OP isn't using an enhanced for loop, and so will never run into issues with concurrent modification. – azurefrog Feb 11 '19 at 20:17
  • @azurefrog yes 11 and 6 :) – Mr.Java Feb 11 '19 at 20:18
  • @ azurefrog I know. But the linked post shows how to do safe remove in the loop. – tsolakp Feb 11 '19 at 20:19

4 Answers4

3

If you are using Java 8+, You can just use ArrayList::removeIf like so :

list.removeIf(i -> i > 5);

ideone demo

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

If you read the documentation for List.remove(), you will see that the elements after index i are shifted to the left. This means that in your current implementation, you are skipping one element after each removal, so if there are two elements next to each other that are larger than 5, only one of them will be removed.

What you can do is to also shift back the current index one step after you remove an element with i--;. Your code would thus become

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);
}

This will output [3, 4, 1], removing all numbers that are larger than 5.

RaminS
  • 2,208
  • 4
  • 22
  • 30
1

If you start the check from end of the array, it's working.

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]

szaift
  • 11
  • 1
0

I imagine that was the exercise to understand how to remove from a list, but otherwise, this is how you could check before adding to it:

  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);
}
Xbreizh
  • 333
  • 4
  • 19