This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
To make it compile, Set should be iterated, not in a for loop.
When I add one Drip object, it compiles and runs. But when I add one more, it throws a class cast exception. Because to add an element to a tree, a second element need to be compared with the first element.
In the TreeSet code, it allows you to add any element as the first node in the tree. But when you add the 2nd, 3rd ... nodes to the tree, this node is cast to Comparator or Comparable. However, Drip is not a Comparable or Comparator. That is why it throws an exception.
Joined: Feb 27, 2012
Thanks for the explanation which I understand, BUT:
This is REALLY weird. Forgive me if it's something stupid that I can't see because I've been staring at it for too long, but I tried this code at work and, like you say, it outputs "Hi".
Yet, when I type the exact same code on my home PC either via Eclipse or notepad, I get the following:
Exception in thread "main" java.lang.ClassCastException: uk.org.dreamboats.certpal.Drip cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
How can that be??? Here's the home version giving the exception:
Joined: Feb 27, 2012
Ok - I'm not going mad - here's the problem.
I recently updated to Java 1.7 at home but am still using 1.6 at work.
There was a known issue in 1.6 that's now been fixed for 1.7 - it should have been causing a ClassCastException
Area: API: Utilities
Synopsis: Due to an error in java.util.TreeMap, it was previously possible to insert invalid null elements and elements not implementing Comparable into empty TreeMaps and TreeSets. Only a single invalid element could be inserted into the empty TreeMaps or TreeSets; additional elements would cause the expected NullPointerException or ClassCastException. Most other operations upon the collection would also fail. As of JDK 7, inserting an invalid null element or an element not implementing Comparable into an empty TreeMap or TreeSet throws a NullPointerException.