Sunday, 29 July 2012

Copying and Cloning Sets: public Object clone()


Calling the clone() method of a HashSet creates a shallow copy of that HashSet.(the elements of the set aren't duplicated. Both sets will refer to the same elements).


import java.util.HashSet;
import java.util.Set;

public class CloningSet {

 public static void main(String[] a) {

  /** Creating a HashSet object **/

  Set set = new HashSet();

  /** Adding elements to the HashSet **/

  set.add("A");
  set.add("B");
  set.add("C");
  set.add("D");

  /**
   * clone() - Returns a shallow copy of this HashSet instance: the
   * elements themselves are not cloned.
   **/
  Set set2 = ((Set) ((HashSet) set).clone());

  System.out.println(set2);
 }
}


The output is:


[D, A, B, C]

No comments:

Post a Comment