The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Collections  [7 examples]

e347. Creating a Copy of a Collection

These examples create a shallow copy of a collection. That is, the new collection contains references to same objects as the source collection; the objects are not cloned.
    List stuff = Arrays.asList(new String[]{"a", "b"});
    
    // Make a copy of a list
    List list = new ArrayList(stuff);
    List list2 = new LinkedList(list);
    
    // Make a copy of a set
    Set set = new HashSet(stuff);
    Set set2 = new TreeSet(set);
    
    // Make a copy of a map
    Map map = new HashMap();
    // Add key/value pairs ...
    Map map2 = new TreeMap(map);

 Related Examples
e342. Implementing a Queue
e343. Implementing a Stack
e344. Implementing a Least-Recently-Used (LRU) Cache
e345. Listing the Elements of a Collection
e346. Storing Primitive Types in a Collection
e348. Making a Collection Read-Only

See also: Arrays    Bits    Dates    Hash Tables    Lists    Property Files    Sets    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.