How to remove a specific array from an ArrayList

Javasaurusrex :

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
YCF_L :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143942&siteId=1