This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Which one is better to use < or compareTo() ?  RSS feed

 
Vector Sanasam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found that the binary operator < works with Integer wrapper objects for comparison.
So if i have two Integer objects like this:

which method of comparison is better?

or this
 
Stephan van Hulst
Saloon Keeper
Posts: 7807
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The two do different things. To get the boolean result, you'd still need to apply a relational operator: x.compareTo(y) < 0

The relational operators don't actually work on boxed integers. The values get unboxed before the operator is applied.
 
Gabrielle Linkherz
Greenhorn
Posts: 26
Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmm .. I always use > for integer, and compareTo() for String or Char
 
Campbell Ritchie
Marshal
Posts: 55707
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:. . . The relational operators don't actually work on boxed integers. . . .
But what about == and != ? Those work completely differently for wrapper objects. I would suggest you stick to using methods for all reference types, not < nor <= nor > nor >= nor == nor !=.
 
Campbell Ritchie
Marshal
Posts: 55707
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gabrielle Linkherz wrote:. . . I always use > for integer, . . .
Do you mean integer or int or Integer? All three are different.
Char
What is a Char? For chars, you cannot use compareTo because they are primitives. There is no such class as Char in the standard API; maybe you mean Character.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!