aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes when and how is compareTo() called for each element Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "when and how is compareTo() called for each element" Watch "when and how is compareTo() called for each element" New topic
Author

when and how is compareTo() called for each element

saurabhthard aggarwal
Greenhorn

Joined: Nov 20, 2008
Posts: 22
//PLEASE EXPLAIN TO ME WHICH IS THE CALLED OBJECT AND WHICH IS THE CALLING OBJECT ,WHY

Byju Joy
Ranch Hand

Joined: Sep 06, 2005
Posts: 84
Song2.compareTo method is not at all called in this case. Because Song2 objects are added to ArrayList, which is not 'sorted' and hence doesn't need compareTo method implementation. However if Song2 objects were being added to a sorted collection such as TreeSet, then compareTo would have been called. In that case 'caller' will be TreeSet object, and called on Song2 objects.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874



Song2.compareTo method is not at all called in this case. Because Song2 objects are added to ArrayList, which is not 'sorted' and hence doesn't need compareTo method implementation. However if Song2 objects were being added to a sorted collection such as TreeSet, then compareTo would have been called. In that case 'caller' will be TreeSet object, and called on Song2 objects.


I m afraid. compareTo () method is called when Collections.sort() is called .



Here ArrayList contains Song2 objects which implements comparable interface. Collections.sort() will actually compareTo() method to sort it .
saurabhthard aggarwal
Greenhorn

Joined: Nov 20, 2008
Posts: 22
According to K&B SCJP 6 Collections.sort() method will call compareTo() of comparable interface.
Input of the program is unsorted.

Output of the program is sorted.

Do you have any idea of how compareTo() is used inside sort() method.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874



Did you had look at API ? Collection sort() . Check it out
Byju Joy
Ranch Hand

Joined: Sep 06, 2005
Posts: 84
Collections.sort is not the only place which can trigger compareTo call. In the code below compareTo is called without Collections.sort. In a sorted collection while trying to insert a new item a suitable place is to determined by comparing the new item with existing items.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: when and how is compareTo() called for each element
 
Similar Threads
Sorting on int field of object
Hashcode not removing duplicates from set
Collections.sort() on Array List
Head First Java HashSet
Unexpected Exception