简体   繁体   English

使用 addAll 在哈希集中添加列表

[英]add a list in a hashset using addAll

In java im not able to add a list to a hashset using hash set addAll method在 java 中,我无法使用 hash set addAll 方法将列表添加到 hashset

List a = new ArrayList();
a.add(20);

List b = new ArrayList();
b.add(30);

Set set = new HashSet ( a );

set.addAll( b);

Please help请帮忙

Thanks谢谢

I tried your code and it works for me.我试过你的代码,它对我有用。

One thing though - it would be better to use the generic versions of the collections.不过有一件事 - 最好使用集合的通用版本。 This removes the warnings.这将删除警告。

List<Integer> a = new ArrayList<Integer>();
a.add(20);

List<Integer> b = new ArrayList<Integer>();
b.add(30);

Set<Integer> set = new HashSet<Integer>(a);
set.addAll(b);

This works fine, just that if you add a list to the set, the repeated elements between the list and the set are added just once.这工作正常,只是如果您向集合中添加一个列表,则列表和集合之间的重复元素只会添加一次。

Say for example ArrayList arr has elements 2,3,4 and HashSet set has elements 2,5,7 now if you do set.addAll(arr), then set still includes 2,5,7,3,4.比如说 ArrayList arr 有元素 2,3,4 并且 HashSet set 现在有元素 2,5,7 如果你执行 set.addAll(arr),那么 set 仍然包括 2,5,7,3,4。

Also Imagine a scenario where you have an ArrayList arr and HashSet set where T is a generic class containing several parameters, then common elements in the final set will be removed as per equals method's overridden definition in T class and the element added to set will be persisted in the final set over the element in the arraylist.还想象一个场景,你有一个 ArrayList arr 和 HashSet 集合,其中 T 是一个包含多个参数的泛型类,然后最终集合中的公共元素将根据 T 类中的 equals 方法的重写定义被删除,并且添加到集合的元素将是保留在数组列表中元素的最终集合中。

你可以简单地这样做:

Set<String> set = new HashSet<String>(list);
    ArrayList<Integer> arr = new ArrayList<>();
    arr.add(20);
    arr.add(30);
    arr.add(40);
    System.out.println(arr); //[20, 30, 40]

    ArrayList<Integer> arr2 = new ArrayList<>();
    arr2.add(10);
    arr2.add(70);
    arr2.add(40);
    
    System.out.println(arr2); //[10, 70, 40]
    arr2.addAll(arr);

    System.out.println(arr2); //[10, 70, 40, 20, 30, 40]

    HashSet<Integer> set = new HashSet<>(arr);
    System.out.println(set); //[20, 40, 30]
    set.addAll(arr2);
    ArrayList<Integer> dummy = new ArrayList<>(set);

    System.out.println(dummy); //[20, 70, 40, 10, 30]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM