Baker1562 Baker1562 - 2 months ago 10
Java Question

Removing an element from a List<String[]> not working as expected

I have an ArrayList of String arrays which is added to like so:

List<String[]> data = new ArrayList<>();
data.add(new String[] {var, lex, valor});


When trying to erase one of the String arrays the output is
false
for some reason. Here's how I remove it:

data.remove(new String[] {var, lex, valor});


I've also tried removing using position, the method is as follows:

public void eliminarPos(String var, String lex, String valor, Integer ii) {
boolean uno = data.remove(ii);
System.out.println(uno);
}


The output for the method above is
false
. Is there any way to successfully remove the String array from the ArrayList?

Answer

remove by String array will not work, as list.remove calls equals() on the object. In case of array.equals it is just reference comparison (==).

Remove by position works and you have to specify the right index as primitive int.

public void eliminarPos(String var, String lex, String valor, int ii) {
    String[] uno=data.remove(ii);
    System.out.println(uno);
}