aspose file tools*
The moose likes Beginning Java and the fly likes collections              addAll method !!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "collections              addAll method !!!!" Watch "collections              addAll method !!!!" New topic
Author

collections addAll method !!!!

amit patidar
Greenhorn

Joined: Jul 10, 2009
Posts: 12
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

Joined: Oct 27, 2005
Posts: 19755
    
  20

If you want unique values only use a Set: HashSet, LinkedHashSet or TreeSet.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9311
    
  17

Looking at your requirement, you can do this



Also please Use Code Tags when posting a source code...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
amit patidar
Greenhorn

Joined: Jul 10, 2009
Posts: 12
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

Joined: Oct 27, 2005
Posts: 19755
    
  20

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

Joined: Jul 10, 2009
Posts: 12
i will have a look on other collection types

but now the view is clear

Thank you Rob
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: collections addAll method !!!!