0

I have question about JDK8 and Consumer class. As I've understood Consumers they provide a method which executes things on the argument of the accept() method.

Could someone explain why the following code is throwing IndexOutOfBoundsException?

` public static void main(String[] args) {

    List<Integer> integerList = new ArrayList<Integer>();
    List<Integer> integerList2 = new ArrayList<Integer>();

    Consumer<List<Integer>> adder = integers -> {
        integers.add(Integer.MAX_VALUE);
        integers.add(Integer.MIN_VALUE);
    };
    Consumer<List<Integer>> remover = integers -> {
        integers.remove(Integer.MAX_VALUE);
        integers.remove(Integer.MIN_VALUE);
    };


    adder.accept(integerList);
    adder.accept(integerList2);
    remover.accept(integerList);

    if (integerList.contains(Integer.MAX_VALUE)) {
        System.out.println("YES");
    }
    if (integerList2.contains(Integer.MIN_VALUE)) {
        System.out.println("ALSO YES");
    }
}`

I expect it to add two values to integerList and interList2 and then remove two values from integerList. This should print out "ALSO YES".

  • 1
    Because there is also a `remove(int index)` overload and your code uses that. You have to to go `Integer` instead of `int` first. Btw, this has nothing to do with the consumers. `remove(Integer.valueOf(foo))` – Zabuzard Jun 02 '23 at 21:08

0 Answers0