File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Collection comparable(i) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Collection comparable(i)" Watch "Collection comparable(i)" New topic
Author

Collection comparable(i)

veena bijur
Ranch Hand

Joined: May 16, 2011
Posts: 67



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.







Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: May 16, 2011
Posts: 67


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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection comparable(i)
 
Similar Threads
TreeSet - Comparable
Still not getting working of compareTo() method
Still trying to understand compareTo() method
sorting in Collection
Sorting Keys(Value Objects) in HashMap