Add a list to hashset using addAll

In java, I m cannot add the list to hashset using the addAll hash 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

+4
source share
2 answers

I tried your code and it works for me.

One thing though - it would be better to use generic versions of 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); 
+12
source

This works fine only if you add the list to the set, duplicate items between the list and the set are added only once.

Say, for example, ArrayList arr has elements 2,3,4, and the HashSet now has elements 2,5,7, if you do set.addAll (arr), and then the set still includes 2,5,7,3, 4.

Also imagine where you have installed ArrayList arr and HashSet, where T is a common class containing several parameters, then the common elements in the final set will be deleted by the method of the overridden equals method in the class T, and the element added to set will be saved in the final set over an element in an arraylist.

+1
source

Source: https://habr.com/ru/post/1339743/


All Articles