• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

collections addAll method !!!!

 
amit patidar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

public static void main(String[] args) {

List<Integer> listA = new ArrayList<Integer>();
List<Integer> listB = new ArrayList<Integer>();

listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);

listB.add(1);
listB.add(2);


listA.addAll(listB);

for(Integer ele : listA){
System.out.print(ele);
}

}


Program prints values from both the list (listA and listB) (1,2,3,4,1,2).

or the result should be union of listA and listB ie listA Union listB ie (1,2,3,4)

Please Help.
 
Rob Spoor
Sheriff
Pie
Posts: 20659
64
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want unique values only use a Set: HashSet, LinkedHashSet or TreeSet.
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looking at your requirement, you can do this



Also please Use Code Tags when posting a source code...
 
amit patidar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so this is not the implementation of addAll() method which helps in union of the result , these are the property of Set implementation classes which maintains unique elements

so this is clear that only Set: HashSet, LinkedHashSet or TreeSet have this case , all other collections implementing addAll() will give complete result ie listone +listtwo+..................listn
 
Rob Spoor
Sheriff
Pie
Posts: 20659
64
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It determines on the Collection type whether or not it will contain duplicates.

For List, yes, you will get all elements from all lists, with duplicates. In the end, result.size() == list1.size() + list2.size() + ... + listn.size().
Set will only contain one copy of each value, so it will really be the union.
Queue and Deque behave a bit like List I believe.
Other collection types, who knows. Check the API of the type to see what it tells you.
 
amit patidar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i will have a look on other collection types

but now the view is clear

Thank you Rob
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic