【问题标题】:Distinguishing between ArrayList#remove() methods区分 ArrayList#remove() 方法
【发布时间】:2014-03-16 02:07:01
【问题描述】:

我有一个整数的 ArrayList;

ArrayList<Integer> list = new ArrayList<>();
list.add(8);
list.add(20);
list.add(50);

我还有一个变量,它被设置为该 ArrayList 中的一个随机项。我想从arraylist中删除变量中的项目,所以我尝试了这个;

list.remove(var);

但是,它假定因为var 是一个整数,它会尝试获取var 位置处的索引,而不是搜索并删除它。但是因为列表中的每个项目都大于它的大小,所以它总是给出一个 ArrayOutOfBoundsException。有没有办法强制 Java 尝试使用正确的 remove 方法?

【问题讨论】:

  • 传递Integer 引用。
  • 如何传递整数引用?
  • var 声明为Integer。或者在方法调用中强制转换。

标签: java arraylist indexing indexoutofboundsexception


【解决方案1】:

您需要传递Integer - 您的主要选择是:

Integer valueToRemove = 8;
list.remove(valueToRemove);

int anotherOne = 20;
list.remove(Integer.valueOf(anotherOne));

int andFinally = 50;
list.remove((Integer) andFinally);

【讨论】:

    【解决方案2】:

    当您调用 add(8) 时,它实际上是自动装箱的,因此实际调用是 add(new Integer(8))。 remove() 调用不会发生这种情况,因为实际上有一个 remove() 调用将 int 作为参数。解决方案是自己创建 Integer 对象,而不是依赖自动装箱:list.remove(new Integer(var))

    【讨论】:

    • 不要打电话给new Integer。曾经。这几乎和打电话给new String 一样糟糕。
    • 无论如何都会产生相同的字节码。
    • 不。 new Integer 创建Integer 的新实例。 Integer.valueOf 将(通常取决于大小)从池中获取Integer
    • 理论上可以这样不同;但是,请注意,从池中查找可能比创建新整数更昂贵,因为它通常是使用字符串。在实践中,重新编译器很可能在这两种情况下都将其优化掉。
    猜你喜欢
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 2018-10-16
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多