LinkedList.clone() bug
Bryce McKinlay
bryce@waitaki.otago.ac.nz
Thu Jul 12 20:20:00 GMT 2001
Brad Fitzpatrick wrote:
> 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:
[...]
> 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.
Thanks for the bug report. The patch isn't correct in the presence of
subsclassing due to the use of new instead of clone - for example if you had
something like:
class MyLinkedList extends LinkedList{}
MyLinkedList l = new MyLinkedList();
Object clone = l.clone();
then the runtime type of the clone will be LinkedList instead of MyLinkedList
as would be expected. This is a mistake I've made in the past while working on
the collections classes ;-)
Instead, I think the correct fix is something like:
Index: LinkedList.java
===================================================================
RCS file: /cvs/gcc/gcc/libjava/java/util/LinkedList.java,v
retrieving revision 1.5
diff -u -r1.5 LinkedList.java
--- LinkedList.java 2000年12月04日 10:20:00 1.5
+++ LinkedList.java 2001年07月13日 03:18:11
@@ -474,7 +474,7 @@
catch (CloneNotSupportedException ex)
{
}
- copy.size = 0;
+ copy.clear();
copy.addAll(this);
return copy;
}
I havn't tested this, however. Could you try it out and get back to me?
regards
[ bryce ]
More information about the Java
mailing list