ArrayList数据类型中的remove()方法究竟返回了什么

时间:2018-01-01 11:23:35

标签: java arraylist

我在我的代码中使用list.remove()方法。我试图将返回的值作为参数传递给某个函数作为字符串,这样它既可以返回也可以删除对象。当我在for循环中打印它时,它只显示两个元素,它应该打印4。为什么会这样?

JSON.stringify({'_id': id,  'username': username,   'password': password}),
  
    

D /删除++++++++++++++++++++++++      d /移除+++++++++++:++++ç

  

为什么只在打印a,b,c,d?

时打印a和c

4 个答案:

答案 0 :(得分:7)

它返回已删除的元素,如Javadoc中所述:

  

E java.util.List.remove(int index)

     

返回:
之前位于指定位置的元素

它只打印" a"和" c"因为它只删除了#34; a"和" c"。

ArrayList中删除元素时,以下元素的索引会递减。如果您希望循环删除所有元素,则必须考虑到这一点。否则你将跳过一半的元素。

for(int i=0;i<list.size();i++) {
    Log.d("Removed+++++++++++","++++"+list.remove(i));
    i--;
}

答案 1 :(得分:3)

正如Java API文档所述:

E remove(int index) - 删除此列表中指定位置的元素(可选操作)。将任何后续元素向左移位(从索引中减去一个)。返回从列表中删除的元素。

如果您不想在下一个循环中增加要删除的元素的索引,可能需要将循环更改为while循环,因为在您的示例中它似乎是不必要的(它在for循环中导致问题,你没有再次在循环中减少这个索引。)

ArrayList<String> list = new ArrayList<>(); list.add("a");
list.add("b");
list.add("c");
list.add("d");
while (list.size() > 0) {
    Log.d("Removed+++++++++++","++++" + list.remove(0)); // queue.remove();
}

答案 2 :(得分:0)

实际上,从ArrayList中的loop对象列表中删除值后,列表的大小会减小,而for loop索引值会增加1,因此在删除两个值后,列表大小保持为2,i值为2,因此条件失败并且循环终止。

尝试以下代码:

ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");

while(list.size() > 0){
    String removingValue = list.get(0);
    if(list.remove(0) != null)
        System.out.println("After removing " + removingValue + " list size is : " + list.size());
}

,输出如下:

After removing a list size is : 3
After removing b list size is : 2
After removing c list size is : 1
After removing d list size is : 0

希望你的逻辑清除。

答案 3 :(得分:0)

您应该记住,ArrayList类中有两个remove()方法:

/**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {

另一种删除方法如下所示:

/**
     * 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.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(Object o) {