• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on syntax and how Collections.sort is working  RSS feed

 
Swapna latha
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I have seen a code like below in tutorialspoint.com but couldnot understand it:

Here in the method sort, one of the parameter is list and the other is a class Comparator, but question is what is the meaning of new Comparator(){@Override................}. and what is this called as , i mean override, or constructor override, any name for this please.

Thanks & Regards,

Swapna
 
Paul Clapham
Sheriff
Posts: 22838
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Name: "anonymous inner class".
 
praveen kumaar
Ranch Hand
Posts: 461
22
Android Chrome Eclipse IDE Google App Engine Java Notepad Oracle Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi swapna,
Please UseCodeTags for inserting any code in your post.
here the sort method will let sort the collection(list in your case) according to the comparator.if you would not give it the comparator argument then the sort will be performed according to the natural ordering(accordingly with the comparable implementation means the natural ordering is determined as comparable compareTo method so the elements in the comparable must implement comparable interface for determining natural ordering).but sometimes we can face a situation when we do not want to sort the collection as per natural ordering but on some another basis.here the interface Comparator help us,we can define a strategy for comparing the instances by overriding its Compare method.
In your code new Comparator() {@Override...} is a anonymous class(it does not have name) which is implementing the Comparator interface and inside its class body it is overriding the interface Compare method.
here is the example:

you can see the difference at line 25 and 32.at line 25 the sort is performed according to the employee id(natural ordering,here it uses a comparable compareTo method) and at line 32 the sort is performed according to the length of the employee name(here the Comparator compare() method is used to find the ordering criteria).

Hope it helps!

kind regards,
Praveen
 
Swapna latha
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:Name: "anonymous inner class".


Thanks Paul.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!