How can I create a Collection based on another Collection?

Brandon Rohlfs

Every concrete implementation provides a constructor, which takes a Collection as an argument. Care must be taken when creating a Collection based another Collection, this is because depending on the target concrete implementation being created, specific rules regarding duplicates may be be enforced. Such as creating a Set based on a List.

The following is a short list of the constructors provided by some of the concrete Classes of the JCF (Java Collections Framework), which enable the creation of a Collection based an another implementation.

ArrayList(Collection<? extends E> c) 
LinkedList(Collection<? extends E> c) 
Vector(Collection<? extends E> c) 
TreeSet(Collection<? extends E> c) 

Creating a Collection based on another Collection is quite easy. The hard part is knowing which Collection to use based on performance and other issues.

For example the ArrayList created will contain the same elements in the same order as the first ArrayList created.

List<String> slist = new ArrayList<String>(); 
slist.add("g"); 
slist.add("a"); 
slist.add("d"); 
slist.add("a");
slist.add("f");
slist.add("e");
slist.add("c");
slist.add("b");
   
for(String s : slist){  
 System.out.print(s + "	");  
}
System.out.println();  
List<String> s2list = new ArrayList<String>(slist);  
for(String s : s2list){  
 System.out.print(s + "	");  
}
When creating a Set based on an existing List the Set will be void of duplicates.
List<String> slist = new ArrayList<String>(); 
slist.add("g"); 
slist.add("a"); 
slist.add("d"); 
slist.add("a");
slist.add("f");
slist.add("e");
slist.add("c");
slist.add("b");
   
for(String s : slist){  
 System.out.print(s + "	");  
}
System.out.println();  
Set<String> s2set = new TreeSet<String>(slist);  
for(String s : s2set){  
 System.out.print(s + "	");  
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact