• 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

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: 15510
363
  • 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: 79180
377
  • 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: 79180
377
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic