Removing an element from a List not working as expected

前端 未结 3 1201
我寻月下人不归
我寻月下人不归 2021-01-24 21:54

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

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


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-24 22:39

    If you take a look at the Javadocs, you'll see that there are 2 different overloaded methods for remove. One takes an Object, the other a primitive integer as position:

    remove

    public E remove(int index)

    Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

    The above takes a primitive integer, the below takes an Object:

    remove

    public boolean remove(Object o)

    Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged...

    The reason why you see false is because you supply the wrapper class of primitive int. Integer is an Object, thus Java uses the method that most closely resembles the way you call it, and in this case you call with an Object parameter. Java then uses method signature remove(Object o), and since the specified Integer doesn't exist in the ArrayList, it returns false.

    Now, the reason why the latter fails is that you create a new String array, thus a new instance. Since new String[] { var, lex, valor } and new String[] { var, lex, valor } are not referentially equal, Java does not find the same Object in the ArrayList and does not remove the item. The solution is to use primitive int:

    public void eliminarPos(String var, String lex, String valor, int ii) {
        String[] uno = data.remove(ii); //Make sure to use String[], as different types are returned
        System.out.println(uno);
    }
    

    Java will then use the method that takes in a primitive integer because you pass a primitive integer. The reason why you see incompatible types: String[] cannot be converted to boolean is because remove(int index) returns the actual Object at the position specified, or the removed object, not a boolean like remove(Object o) does.

提交回复
热议问题