• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Collection comparable(i)  RSS feed

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Please tell me the follow,


how compareTo(Object obj) works, comparison taking place between which all objects?
current object with specified object, i did nt get which is the current one and specified one .please clarify.







 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When sorting objects, such as with Collections.sort(), the sort method picks two objects to compare, A and B, and does something like:


It does this as many times as needed with as many pair of objects, until the list is sorted.
 
veena bijur
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Thanks a lot.


Does it picks elements randomly and compare, how is the exact working of compareTo()



age takes what value is that 1st object data member?
st.age takes what value is that 2nd object data member?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

veena bijur wrote:Does it picks elements randomly and compare



Not in any particular sorting algorithm(⇐click) that I know of, but, one could certainly do it that way.

how is the exact working of compareTo()



Its behavior is exactly how the docs describe it (if you write it correctly).

How you implement that behavior (that is, how you make it behave that way) is up to you. It depends on what you decide it means for one object of your class to be "less than" or "greater than" another.




age takes what value is that 1st object data member?
st.age takes what value is that 2nd object data member?



There is no "first object" and "second object." It's just a method call, exactly like any other. You might be thinking of Comparator.compare(Object o1, Object o2). That's a different method that serves a similar purpose.

Note that there are at least 2 problems with your little sample method:

1) No braces around the if body.

2) You're only fulfilling part of the contract of the compareTo() method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!