• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confusion in compareTo()  RSS feed

 
Vishal Hegde
Ranch Hand
Posts: 1078
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Ranchers,

I have one doubt in the below code


does this mean

current<joining

??
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, otherwise the code would have read current < joining instead of what it is now.

'current' is an object which has a member variable named 'compare'.
'compare' is something with a 'compareTo' method.
That method is called, with 'joining' as the argument.
Then there's a check to see if the result returned by 'compareTo' is less than zero.

What are 'current' and 'joining'? Without more information we can't tell you what the exact purpose of that line of code is.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal Hegde wrote:does this mean
current<joining

I'm going to disagree with Jesper here, because I think what you meant is
current "less than" joining
and if that is, indeed, what you meant - in whatever way you determine "less than" - then the answer is: yes.

His point is well made though: you should be very careful when you use symbols like '<', because they have a very specific meaning in the Java language, and they cannot be used with objects.

Winston
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surely it means compare returns a negative value when you pass joining?
It just goes to show how confusing code can be with lots of .s; it would have been better for those fields to have private access. Then any such comparisons would be like nepotism:





Best kept within the family.
 
Rafael Prado Oliveira
Greenhorn
Posts: 28
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Return of the compareTO method
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.



and this result is comparing to 0
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!