• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Writing compareTo and equals method with Object arguments

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No worries, I didn't cross-post. Here is the data I'm given:


I now have to create a compareTo method and equals method using Objects as arguments. I have to compare course names using those methods. Here is my attempt. What am I doing right/wrong? Thanks in advance!



 
Greenhorn
Posts: 13
Android Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:



Assuming that Name is the only attribute that determines equality between your objects (and if not, add a check to equals()), the way you have coded equals() should do the trick.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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()?
 
Steve Luke
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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:


Problem with this approach is that compareTo() returns an int, and equals() returns a boolean. The boolean is enough to return a equal/not equal relationship, but not enough to produce an order (if not equal, which one comes first).
 
Jill Ceke
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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()?



I'm so confused now. Ok looking at the Object class, it seems to have an equals method but no compareTo. The CompareTo comes from the Comparable interface? So I'm
overwriting that method provided in the interface. If an object of type string is passed as a parameter can I dont need to cast it to an Integer since the output is an an from
that method, right? So leave out the cast like this **edit** just saw Object class also has toString method so this is better:



Is the equals method correct btw? Also, null is always ranked lower than any char? OOP is so hard to wrap my head around. Thanks!
 
J Steven Perry
Greenhorn
Posts: 13
Android Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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



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 Luke
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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()?


toString() isn't what you should do. How would a String ever compare to a CSClass? Are they ever the same? It is like comparing Apples to Oranges!

If you have to take Object in, then you need to check the type of the Object, then cast to CSClass only if that is a CSClass. If it isn't then you have a whole other can of worms, because what comes first, an expensive orange or a large apple (that is, if the two things aren't the same type then they can't be compared). You might be best off throwing an exception (throw new IllegalArgumentException("The parameter to compareTo is not a CSClass, and you can't compare CSClass to something that is not a CSClass:" + that.getClass().getName());)
 
Marshal
Posts: 79239
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

You cannot expect compareTo() to work in an equals() method. It sometimes does, but sometimes doesn't.
Why are you trying to write a compareTo with Object parameter? That is what we had to write in Java1.4, but it is now Comparable<T>, so it would beWhy are you writing a compareTo() method in that class at all? If you read about Comparable, you find there needs to be a “Natural Ordering”, which your course class doesn't appear to have. You can read more about comparisons and writing compareTo() here. You can usually only compare an object of any class to an instance of the same class.

Writing an equals() method is notoriously difficult. There are three well‑known references:-
  • Joshua Bloch's Effective Java pages 33‑44.
  • Angelika Langer's Java equals and hashCode FAQ (Google it)
  • Odersky Spoon and Venners.
  • If possible, read all three sources because they all give a slightly different view of the problem.
    At least I agree with your teacher here. You must use Object as a parameter for the equals method. The method J Steven Perry gave is correct except for the last line, so I shall give you a correct method, mostly copied from J‍SP's post:-You should know what to write in equals() now you have read those references.
    J‍SP's compareTo method will work only if natural ordering is the same as “ASCIIbetical ordering” of its name.
     
    Jill Ceke
    Greenhorn
    Posts: 8
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Lol that is what our professor required as method parameters. Thanks for the references. I'll keep chugging along.
     
    Campbell Ritchie
    Marshal
    Posts: 79239
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.
     
    J Steven Perry
    Greenhorn
    Posts: 13
    Android Java Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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.



    It was my understanding that using equals() and compareTo() together were required for the exercise.

    I believe the code provided will work fine for what the user needs. Perhaps not in every single case (though if natural ordering were changed, the compareTo() method could be adjusted accordingly), but I didn't claim it would.

    Perhaps I'm misunderstanding the purpose of this forum. I was just trying to be helpful.

    Have a nice day.
     
    Campbell Ritchie
    Marshal
    Posts: 79239
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    It didn't say you had to use compareTo inside equals, however.

    What we all forgot is that you have to override hashCode, too. That will of course have been mentioned in the links I posted yesterday.
     
    Campbell Ritchie
    Marshal
    Posts: 79239
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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?
     
    J Steven Perry
    Greenhorn
    Posts: 13
    Android Java Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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?



    Obviously, modify the criteria for what compareTo() does:

     
    J Steven Perry
    Greenhorn
    Posts: 13
    Android Java Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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()



    Generics have been around for a long time now, so using them is *always* a good idea. But if you are forced by your instructor to write suboptimal code , then your class would like something like this:



     
    Campbell Ritchie
    Marshal
    Posts: 79239
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    J Steven Perry wrote: . . . But if you are forced . . . to write suboptimal code . . .

    Couldn't agree more.
    reply
      Bookmark Topic Watch Topic
    • New Topic