6

当我在 Java 中使用 ArrayList 时,有些东西我不明白。这是我的初始化代码:

 ArrayList<Integer> list = new ArrayList <Integer> ();
list.add (0);
list.add (1);

有时我需要通过索引删除对象:

list.remove (0) // delete the object in the first box

但有时我想通过其内容删除一个对象:

list.remove (0) // delete the object HAS Which value of 0

这段代码非常模棱两可。为了阐明我想在代码中执行的操作,我指定了这样的类型:

list.remove ((Object) 0) // delete the object which has a value of 0

如果我不交流,唯一知道调用了哪些方法的方法是将鼠标指针放在方法上查看: java.util.ArrayList.remove boolean (Object object)

Java 但是它有什么不同呢?有方法指针吗?有没有一种不那么模棱两可的方法来做到这一点?

非常感谢,对不起我的英语。

PS:我应该说我终于使用了 SparseIntArray 但我很好奇

4

4 回答 4

12

对于陈述者。List#remove(index)返回从列表中删除的对象。List#remove(Object)返回一个布尔值。

然而,在这种特殊情况下。你可以做。

 ArrayList<Integer> list = new ArrayList <Integer> ();
        list.add (0);
        list.add (1);
        System.out.println(list.remove(new Integer(0)));
于 2013-02-27T16:29:19.717 回答
2

每当 Java 中存在歧义时(当多个方法签名可以在编译时匹配参数的类型时),使用强制类型转换来选择正确的方法是您唯一的选择。当然,您可以在实际调用之前将参数转换并存储到正确类型的局部变量中,但这并不能让读者更清楚 - 在我看来,将参数直接转换到使用它的位置是最好的选择,明确调用哪个方法。

By the way the reason the API is so ambiguous in this case is that at the time the API was made, there was no Auto-Boxing so it was not possible to write ambiguous code like this in the first place. However changing the method to make it unambiguous would have been a breaking change. Since storing Integer in an ArrayList isn't that great of an idea anyway most of the time, they decided to let us live with that slight annoyance.

于 2013-02-27T16:36:46.713 回答
2

If it is just the ambiguity with the remove() method in Integer ArrayList is bothering you, you can extend the ArrayList to implement your own :

public class MyIntArrayList extends ArrayList<Integer> {

    boolean removeByObject(Integer intObj) {
        return super.remove(intObj);
    }

    Integer removeByIndex(int index) {
        return super.remove(index);
    }

}
于 2013-02-27T16:43:02.617 回答
0

You could use list.remove(new Integer(0)) to surely remove the object

于 2013-02-27T16:44:39.480 回答