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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With