File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when and how is compareTo() called for each element

 
saurabhthard aggarwal
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//PLEASE EXPLAIN TO ME WHICH IS THE CALLED OBJECT AND WHICH IS THE CALLING OBJECT ,WHY

 
Byju Joy
Ranch Hand
Posts: 84
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 874
Android Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 874
Android Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Did you had look at API ? Collection sort() . Check it out
 
Byju Joy
Ranch Hand
Posts: 84
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic