2

i.e if ArrayList contains coordinates {0, 0} remove them.

Code test below fails as expected.

ArrayList<int[]> array = new ArrayList<>();

int[] arr1 = new int[]{0, 0};
int[] arr2 = new int[]{1, 1};

array.add(arr1);
array.add(arr2);

System.out.println("Before " + array.contains(arr1)); // true

int[] arr3 = new int[]{0, 0};

array.remove(arr3);

System.out.println("After " + array.contains(arr1)); //true
5
  • 2
    System.out.println("After " + array.contains(arr1)); //true - actually that prints After false, since you are removing the exact same array instance you added to the List. Commented Sep 4, 2019 at 5:30
  • 1
    Code runs fine as expected. Your last line prints false Commented Sep 4, 2019 at 5:30
  • See this :howtodoinjava.com/java/collections/arraylist/… Commented Sep 4, 2019 at 5:32
  • try printing array.contains(arr3) just before removing it Commented Sep 4, 2019 at 5:47
  • Note: remove only removes first found element (if it would work with arrays) Commented Sep 4, 2019 at 5:55

1 Answer 1

3

You can use removeIf like so :

array.removeIf(a-> a[0] == 0 && a[1] == 0);

or you can use :

array.removeIf(a -> Arrays.equals(a, new int[]{0, 0}));

Of if you want to remove all the arrays which contains only zeros you can use :

array.removeIf(a -> Arrays.stream(a).allMatch(value -> value == 0));

After the edit of the OP the solution can be like so :

array.removeIf(a -> Arrays.equals(a, arr3));
Sign up to request clarification or add additional context in comments.

5 Comments

@raviraja the OP ask to remove each array in the ArrayList which hold {0, 0}, maybe he/she gives the wrong example
we can rather use this statement array.removeIf(a->a.equals(arr1)); . why use Array class?
@SujayMohan no, equals doesnt check element by element but it check the reference you can check the two examples here ideone.com/jTNlmK and ideone.com/6NJWAT
@SujayMohan and that is the same that remove() does
@SujayMohan in your example it will remove the correct array because you will remove an existing array, but the general idea of the OP is to any array which hold {0, 0}, the OP edit his/her answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.