Comparing extended objects

Normally I'm not completely clueless with generics, but this one has me stumped. Consider the following code, which compiles and runs cleanly without generics:

publicclass Fooimplements Comparable{

publicint bar;

publicint getBar(){return bar;}

publicint compareTo(Object obj){

return getBar() - ((Foo)obj).getBar();

}

}

-

publicclass ExtendedFooextends Foo{

publicint blah;

}

-

publicstaticvoid main(String[] args){

ArrayList arr =new ArrayList();

Foo f =new Foo();

f.bar = 0;

arr.add(f);

f =new ExtendedFoo();

f.bar = 1;

arr.add(f);

Collections.sort(arr);

}

But how do you make it compile with generics?

[1750 byte] By [leptogenesisa] at [2007-11-27 10:27:31]
# 1

public class Foo implements Comparable<Foo>{

// ...

public int compareTo(Foo obj)

ejpa at 2007-7-28 17:46:14 > top of Java-index,Core,Core APIs...
# 2

Thanks for the reply. I guess that makes sense...but I still have a question. At one point in my (original, far more complicated) code I was trying to set

ArrayList<Foo> a = new ArrayList<ExtendedFoo>();

I guess that was my real mistake...I guess that's illegal because if it were, you could then have one piece of code that thinks the list referenced by a contains only ExtendedFoo while some other piece is putting Foos in it.

So the question is, is there a way to start with an ExtendedFoo list and sort of cast it so that I can start using it like a regular Foo list? (besides using addAll...I don't want my code to be asymptotically slower)

leptogenesisa at 2007-7-28 17:46:14 > top of Java-index,Core,Core APIs...
# 3

> ArrayList<Foo> a = new ArrayList<ExtendedFoo>();

That doesn't make any sense, as you said. Why can't you just call it ArrayList<ExtendedFoo>?

ejpa at 2007-7-28 17:46:15 > top of Java-index,Core,Core APIs...