Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a list in a hashset using addAll

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

like image 474
Pradyut Bhattacharya Avatar asked Feb 14 '11 22:02

Pradyut Bhattacharya


2 Answers

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);
like image 164
Mark Byers Avatar answered Sep 23 '22 02:09

Mark Byers


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.

like image 20
himani1349 Avatar answered Sep 22 '22 02:09

himani1349