This is the mail archive of the java-patches@gcc.gnu.org mailing list for the Java project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

clone() fixes for TreeMap & TreeSet


Jon Zeppieri (Thanks Jon!) pointed out the clone() implementations in the new TreeMap and
TreeSet were incorrect in the presence of subclassing. I was using "new" to create the
copies instead of super.clone(), which would result in a ClassCastException when someone
called clone() on a subclass, because the type of the Object returned from clone would not
be what was expected.

This patch fixes the problem.

regards

  [ bryce ]


2001-02-16  Bryce McKinlay  <bryce@albatross.co.nz>

	* java/util/TreeSet.java (clone): Made subclass safe, use 
	super.clone(), not new.
	* java/util/TreeMap.java (clone): Likewise.

Index: java/util/TreeMap.java
===================================================================
RCS file: /cvs/gcc/egcs/libjava/java/util/TreeMap.java,v
retrieving revision 1.2
diff -u -r1.2 TreeMap.java
--- TreeMap.java	2001/02/14 05:32:31	1.2
+++ TreeMap.java	2001/02/16 01:40:41
@@ -178,8 +178,14 @@
 
   public Object clone()
   {
-    TreeMap copy = new TreeMap();
-    copy.comparator = comparator;
+    TreeMap copy = null;
+    try
+      {
+        copy = (TreeMap) super.clone();
+      }
+    catch (CloneNotSupportedException x)
+      {
+      }
     copy.fabricateTree(size);
 
     Node node = firstNode();
@@ -991,6 +997,9 @@
 		parent.right = node;
 		parent = nextparent;
 	      }
+
+	    // We use the "right" link to maintain a chain of nodes in 
+	    // each row until the parent->child links are established.
 	    if (last != null)
 	      last.right = node;
 	    last = node;
Index: java/util/TreeSet.java
===================================================================
RCS file: /cvs/gcc/egcs/libjava/java/util/TreeSet.java,v
retrieving revision 1.2
diff -u -r1.2 TreeSet.java
--- TreeSet.java	2001/02/15 03:59:57	1.2
+++ TreeSet.java	2001/02/16 01:40:41
@@ -157,7 +157,14 @@
   /** Returns a shallow copy of this Set. */
   public Object clone()
   {
-    TreeSet copy = new TreeSet();
+    TreeSet copy = null;
+    try
+      {
+        copy = (TreeSet) super.clone();
+      }
+    catch (CloneNotSupportedException x)
+      {      
+      }
     copy.map = (SortedMap) ((TreeMap) map).clone();
     return copy;
   }

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]