Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Charting Unknown Waters in JDK 1.4

Java Specialist Dr. Heinz Kabutz has been digging through the classes in the java.util.* package of the JDK 1.4. This article highlights some of the gems he discovered right away.

ondering what I would dig up in the JDK 1.4 source code, I recently started looking through the classes in the java.util.* package—without even the subpackages. That alone kept me busy for most of an afternoon, and although I have not finished exploring that J2SE release yet, I already have enough material for several articles. The following are some of the gems I discovered right away.

Did You Know toString() was Broken for Collections?
In the collection classes, all hell breaks loose when you try to call toString() on a collection that contains itself. For example, consider the following code:

import java.util.Hashtable; public class HashtableTest { public static void main(String[] args) { Hashtable ht = new Hashtable(); ht.put("Heinz", "Kabutz"); ht.put(ht, "all"); ht.put("all", ht); ht.put(ht, ht); try { System.out.println(ht); } catch (StackOverflowError e) { System.out.println("Caused Stack Overflow Error!"); } } }

Running this program under JDK 1.3 or older versions generates a stack overflow. In JDK 1.4, however, the output is:

{Heinz=Kabutz, all=(this Map), (this Map)=all, (this Map)=(this Map)}

This same principle applies to the other collections in JDK 1.4.

Is it a good idea to use a Hashtable as a key, you might ask. Dont forget what happens when the hash code of a key changes during its life (see Issue 031 of The Java(tm) Specialists' Newsletter). Each time a Hashtable changes, its hash code changes as well. So you should not use it as a key. The question I have is why—despite the seemingly limitless amount of stupid code written every day—the people at Sun didn't anticipate programmers adding a collection to itself.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date