为什么list1.remove(0)给出列表中的第一个元素?

时间:2017-07-03 02:04:22

标签: java list

在java课程作业中,我被要求描述以下代码的作用:

while (!list1.isEmpty()) {
list2.add(list2.size(), list1.remove(0));
}

起初我以为这实际上是删除了list1的第一个元素,然后在list2后面添加了剩下的元素。

但是我按照以下方式运行了一个模拟程序:

import java.util.*;

public class testQ1
{
  public static void main(String[] args)
  {
    List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4));
    System.out.println(list1);
    List<Integer> list2 = new ArrayList<>(Arrays.asList(5,6,7,8));
    System.out.println(list2);

    while (!list1.isEmpty())
    {
      list2.add(list2.size(), list1.remove(0));
    }
    System.out.println(list2);
   }
}

它给了我结果:

[1, 2, 3, 4]
[5, 6, 7, 8]
[5, 6, 7, 8, 1, 2, 3, 4]

所以我尝试打印&#34; list1.remove(0)&#34;在while循环之前看看它是什么。然后结果变为:

[1, 2, 3, 4]
[5, 6, 7, 8]
1
[5, 6, 7, 8, 2, 3, 4]

现在打印&#34; 1&#34;什么&#34; list1.remove(0)&#34;是。并按照我之前的想法将剩余的list1合并到list2中。 据我所知,remove(int index)方法用于删除此列表中指定位置的元素。

我的问题是:list.remove(int index)到底给出了什么?

谢谢!

1 个答案:

答案 0 :(得分:5)

List::remove返回已删除的元素。您删除了1,这就是返回的内容。

Always check the docs first for questions like this。该方法的文档说明了返回值表示的内容。有了像Java一样成熟的库,文档将解释99%的问题。

只需删除元素,然后返回列表。

相关问题