Java examples for java.util:Collection Creation
Create and answer a collection that is the same type, or the closest equivalent of another collection.
//package com.book2s; import java.util.*; public class Main { public static void main(String[] argv) { Collection col = java.util.Arrays.asList("asdf", "book2s.com"); System.out.println(createCollection(col)); }/*from w ww . j a v a 2 s .c o m*/ /** * Create and answer a collection that is the same type, or the closest * equivalent of col. * * @param col * @return */ public static Collection createCollection(Collection col) { Collection answer; try { answer = (Collection) col.getClass().newInstance(); } catch (Exception e) { if (col instanceof List) { answer = new ArrayList(); } else if (col instanceof SortedSet) { answer = new TreeSet(); } else if (col instanceof Set) { answer = new HashSet(); } else { answer = new ArrayList(); // should this throw an exception? } } return answer; } }