Java 如何使用集合的 addall() 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3052527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:01:29  来源:igfitidea点击:

how to use addall() method of collections?

javalistcollectionsmerge

提问by bhavna raghuvanshi

i need to use it to merge two ordered list of objects.

我需要用它来合并两个有序的对象列表。

回答by Sjoerd

Collection all = new HashList();
all.addAll(list1);
all.addAll(list2);

回答by polygenelubricants

From the API:

从API:

addAll(Collection<? extends E> c): Adds all of the elements in the specified collection to this collection (optional operation).

addAll(Collection<? extends E> c):将指定集合中的所有元素添加到该集合中(可选操作)。

Here's an example using List, which is an ordered collection:

这是一个使用 的示例List,它是一个有序集合:

    List<Integer> nums1 = Arrays.asList(1,2,-1);
    List<Integer> nums2 = Arrays.asList(4,5,6);

    List<Integer> allNums = new ArrayList<Integer>();
    allNums.addAll(nums1);
    allNums.addAll(nums2);
    System.out.println(allNums);
    // prints "[1, 2, -1, 4, 5, 6]"


On int[]vs Integer[]

int[]VSInteger[]

While intis autoboxable to Integer, an int[]is NOT "autoboxable" to Integer[].

虽然int可以自动装箱到Integer,但int[]不能“自动装箱”到Integer[]

Thus, you get the following behaviors:

因此,您会得到以下行为:

    List<Integer> nums = Arrays.asList(1,2,3);
    int[] arr = { 1, 2, 3 };
    List<int[]> arrs = Arrays.asList(arr);

Related questions

相关问题

回答by ERJAN

I m coding some android, and i found this to be extremely short and handy:

我正在编写一些 android 代码,我发现这非常简短和方便:

    card1 = (ImageView)findViewById(R.id.card1);
    card2 = (ImageView)findViewById(R.id.card2);
    card3 = (ImageView)findViewById(R.id.card3);
    card4 = (ImageView)findViewById(R.id.card4);
    card5 = (ImageView)findViewById(R.id.card5);

    card_list = new ArrayList<>();
    card_list.addAll(Arrays.asList(card1,card2,card3,card4,card5));

Versus this standard way i used to employ:

与我过去使用的这种标准方式相比:

    card1 = (ImageView)findViewById(R.id.card1);
    card2 = (ImageView)findViewById(R.id.card2);
    card3 = (ImageView)findViewById(R.id.card3);
    card4 = (ImageView)findViewById(R.id.card4);
    card5 = (ImageView)findViewById(R.id.card5);

    card_list = new ArrayList<>();
    card_list.add(card1) ;
    card_list.add(card2) ;
    card_list.add(card3) ;
    card_list.add(card4) ;
    card_list.add(card5) ;