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.
Ivan Jozsef Balazs wrote:Well, it is a somewhat funny situation. Albeit the JDK doucmentation lists this compareTo method:
That's because it implements Comparable<String>
Ivan Jozsef Balazs wrote:There seems to exist an overloaded compareTo(java.lang.Object) method as well - maybe a remnant from the good old pre-generic days:
This is down to the way generics are implemented using type erasure. In reality at the p code level there is no compareTo(String anotherString) method it is in fact compareTo(Object anotherString), but the compiler knows that the generic declaration states the parameter must be of type String and so enforces it at compile time. At run time there is no way of checking what type it should be restricted to.
Ivan Jozsef Balazs wrote:
Now this code compiles with 1.4 but not with the newer versions:
That's because prior to Java 1.5 there were no generics and the compareTo method takes an Object as the parameter. From 1.5 onwards the String class was changed to implement the generified Comparable<String> interface and so now the compiler knows that only objects of type String can be passed in to the String classes compareTo() method.