• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

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

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Saloon Keeper
Posts: 13256
292
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 26
Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hmm .. I always use > for integer, and compareTo() for String or Char
 
Marshal
Posts: 73994
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 73994
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic