java - 从 List<String[]> 中删除元素未按预期工作

标签 java string arraylist

我有一个字符串数组的 ArrayList,它是这样添加的:

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

当试图删除其中一个字符串数组时,出于某种原因输出为 false。这是我删除它的方法:

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

我也试过去掉using position,方法如下:

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

上述方法的输出是false。有什么方法可以成功地从 ArrayList 中删除 String 数组吗?

最佳答案

如果你看一下 Javadocs ,您会看到 remove 有 2 个不同的重载方法。一个接受一个对象,另一个接受原始整数作为位置:

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

上面接受一个原始整数,下面接受一个对象:

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...

您看到 false 的原因是因为您提供了原始 int 的包装类。 Integer 是一个 Object,因此 Java 使用与您调用它的方式最相似的方法,在这种情况下,您使用 Object 参数调用。 Java 然后使用方法签名 remove(Object o),由于指定的 Integer 在 ArrayList 中不存在,它返回 false

现在,后者失败的原因是您创建了一个新的 String 数组,因此是一个新实例。由于 new String[] { var, lex, valor }new String[] { var, lex, valor } 在引用上不相等, Java 在 ArrayList 中找不到相同的对象,因此不会删除该项目。解决方案是使用原始 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 将使用接收原始整数的方法,因为您传递的是原始整数。您看到 incompatible types: String[] cannot be converted to boolean 的原因是因为 remove(int index) 返回指定位置的实际对象,或移除的对象,而不是像 remove(Object o) 那样的 boolean

关于java - 从 List<String[]> 中删除元素未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39901616/

相关文章:

java - 在 Java ArrayList 中删除对象 - 耗时

java - 我无法理解如何将数组传递给方法并返回数组列表

Java + UDP + DatagramSocket : Why is a PortUnreachableException thrown, 当 UDP 被设计为无连接时?

java - 需要检查 MaxPermSize : Unrecognized VM option

java - EJB 自动计时器、锁定、超时和长时间运行的方法

python - 如何使用for循环迭代url索引来收集数据

java - 如何在谷歌地图上显示带有坐标的数组列表?

java - RMI-如何通过远程方法传递远程对象?

javascript - 根据分隔符从字符串中提取子字符串

android - 使用 Uri.parse 将字符串转换为 android.net.Uri 是否有效?