Steve
J Steven Perry wrote:First off, you are casting that.getName() to an Integer, which is not correct. Your instincts tell you to use equals() to drive compareTo() behavior are probably right on.
Try this:
Steve
Steve Luke wrote:Think about the possible conditions:
1) What if that is null?
2) What type of Object should that be for the comparison to make sense?
3) What should happen if Object is not that type?
4) What if the name in this is null?
5) What if the name in that is null?
Specifically:
In compareTo() you call that.getName(). that is an Object. Does Object have a method called getName()? What type does getName() return? Should you be casting it to Integer?
In equals, faitly similar. that is an Object. Does Object have a method called getName()?
J Steven Perry wrote:Let me take another shot at this. Consider this code:
After thinking about it some more, maybe equals should be driven off compareTo() (though it's really arbitrary, just make sure not to blow it on the return type like I did in my earlier post).
--jsp
Jill Ceke wrote:Thanks! I would have to pore over this. What if it's required that I pass in "Object that" as the argument for compareTo? Would I have to use the toString() method from Object class instead of getName()?
Steve
Campbell Ritchie wrote:Query that. As I said, equals() must take Object as a parameter, but what are you going to do when you try to compare a course to something else which implements Comparable, e.g. this? I think the most sensible thing then would be to throw an Exception.
Campbell Ritchie wrote:What is going to happen to equals() when you have one course ("Programming", 123) and another ("Programming", 99)? Are two Programming courses equal or not when different numbers of people attend?
Jill Ceke wrote:
Thanks! I would have to pore over this. What if it's required that I pass in "Object that" as the argument for compareTo? Would I have to use the toString() method from Object class instead of getName()
Couldn't agree more.J Steven Perry wrote: . . . But if you are forced . . . to write suboptimal code . . .
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |