[Logo]
Forums Register Login
Collection comparable(i)



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.







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.


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?
 
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.
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Dec 14, 2017 21:30:59.