Wednesday Java Quiz
(Mark Volkmann suggested this quiz.)
Q: Will the following Java source compile, run without exceptions?
import java.util.SortedMap; import java.util.TreeMap; public class Main { public static void main(String[] args) { SortedMap sm = new TreeMap(); sm.put("one", 1); sm.put(2, "two"); System.out.println("value for one is " + sm.get("one")); System.out.println("value for 2 is " + sm.get(2)); } }
Strict rules: No actually running the Java compiler.
Re: Wednesday Java Quiz
That's correct! But is that what it should do ... if you were in charge of designing the behavior? It seems to me that it should work. It can't compare the Integer 2 to the String "one", so maybe it should catch the ClassCastException, take that to mean it didn't match any existing key, and add it to the map. Why would this be a bad thing?
Re: Wednesday Java Quiz
There are no type parameters on the TreeMap, so you've indicated you don't care about the typesafety of the members. Trying to compare an Integer and a String is clearly wrong in the vast majority of cases, so I believe it is appropriate to force the user to explicitly define what their own natural ordering of an Integer and String for this to work.
An alternative would be to make SortedMap<K extends Comparable, V> instead of SortedMap<K,V>, but then this would break the ability to provide a Comparator for classes which don't implement Comparable.