5.0 not backwards compatable?

I just compiled some 1.4.2 code in 1.5, and I got a compiler error. It's not a huge deal, and easily fixable, but I just found it odd that it wasn't backwards compatable. It's suppsoed to be, isn't it?

It's code that implements Comparable

publicint compareTo(Object o){

return toString().compareTo(o);

}

compareTo(java.lang.String) in java.lang.String cannot be applied to (java.lang.Object) at line 92, column 25

Just incase this was already fixed, I tried compiling this in the latest 1.6.0_01 and I get the same error. The code looked like it was meant to compare the string versions of the objects if the objects were not of the right type. I suppose this case is no longer even valid using generics in Comparable, but like I said, it should still compile if it worked in 1.4.2.

[984 byte] By [robtafta] at [2007-11-27 2:39:09]
# 1

heh heh I'm surprised that doesn't come up more often. as you found, in 5 onwards, java.lang.String implements Comparable<String> hence the signature of its compareTo method takes an instance of String rather than Object. can't think right now how the VM could be backwards-compatible without some special case code, which isn't particularly nice.

georgemca at 2007-7-12 3:00:54 > top of Java-index,Core,Core APIs...
# 2

> I just compiled some 1.4.2 code in 1.5, and I got a

> compiler error. It's not a huge deal, and easily

> fixable, but I just found it odd that it wasn't

> backwards compatable. It's suppsoed to be, isn't

> it?

No, it's not. Nobody ever said that all code that was compilable with javac 1.4 would be compilable with javac 1.5. Only binary compatibility was guaranteed. That means that you may compile the code you're showing with a 1.4 compiler or with the latest javac if you set the option "-source 1.4".

After compilation, the generated class file will then be usable by all Java programs, even those compiled with Java 5 or 6.

BTW, with or without generics, the code looks so highly suspicious that you should be very glad the compiler finally rejects it. To make any sense, it should look like this, which is fine with every Java version:

public int compareTo(Object o) {

return toString().compareTo(o.toString());

McNeppa at 2007-7-12 3:00:54 > top of Java-index,Core,Core APIs...
# 3

Thanks, that makes sense. It does look a little silly, and like I said, it was an easy fix. I suppose I assumed that the code was backwards compatable because anytime they don't want you using an old method, they just deprecate it, instead of removing it.

I ended up just changing it to use Generics anyway, and by doing that I was able to just remove the offending code altogether.

robtafta at 2007-7-12 3:00:54 > top of Java-index,Core,Core APIs...