开发者

add a list in a hashset using addAll

开发者 https://www.devze.com 2023-02-10 06:00 出处:网络
开发者_Python百科In java i m not able to add a list to a hashset using hash set addAll method List a = new ArrayList();

开发者_Python百科In java i m not able to add a list to a hashset using hash set addAll method

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.

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.


you can simply do like this :

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消