LinkedList.clone() bug

Brad Fitzpatrick brad@danga.com
Wed Jul 11 21:43:00 GMT 2001


Hello,

First off, I want to thank all the gcj developers.... wonderful tool!
Although I'd heard about it for awhile, I didn't use it until today.

When testing my project built with gcj I found the output was different from
the jar I'd built with Blackdown's bytecode compiler.  I traced it down to a
minor bug in the gcj java library, as illustrated by this test case:

/* Test program showing LinkedList.clone() bug */

import java.io.*;
import java.util.*;

class test {
public static void main (String[] args) {
 LinkedList l1 = new LinkedList();
 l1.add("foo");
 l1.add("bar");

 LinkedList l2 = (LinkedList) l1.clone();

 for (ListIterator i = l1.listIterator(); i.hasNext(); ) {
     System.out.println("L1: "+i.next());
 }

 for (ListIterator i = l2.listIterator(); i.hasNext(); ) {
     System.out.println("L2: "+i.next());
 }
}
}


/*******************************

Using Blackdown's javac & java: (expected results)

L1: foo
L1: bar
L2: foo
L2: bar

Using gcj-3.0:

L1: foo
L1: bar
L1: foo
L1: bar
L2: foo
L2: bar
L2: foo
L2: bar

*****************/

--------- cut ----------

Possible Patch ....

--- gcc-3.0/libjava/java/util/LinkedList.java.orig Wed Jul 11 20:50:47 2001
+++ gcc-3.0/libjava/java/util/LinkedList.java Wed Jul 11 20:51:11 2001
@@ -466,14 +466,7 @@
    */
   public Object clone()
   {
-    LinkedList copy = null;
-    try
-      {
- copy = (LinkedList) super.clone();
-      }
-    catch (CloneNotSupportedException ex)
-      {
-      }
+    LinkedList copy = new LinkedList();
     copy.size = 0;
     copy.addAll(this);
     return copy;


Nothing about LinkedList implements clone() so I'm not sure what the
previous code was trying to do.  What seems to be happening is is
effectively:

 try {
   copy = this;
 } catch (..) { }

Which results in effectively:

 copy.addAll(copy);
 return copy;   // with elements doubled, and the same object reference


--
Brad Fitzpatrick
brad@danga.com



More information about the Java mailing list