JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Showing posts with label collection. Show all posts
Showing posts with label collection. Show all posts

Difference between Comparator and Comparable in java collection with example

7:33 AM
Comparable interface: Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method. For example: 1 2 3 4 5 6 7 public class Country implements Comparable {        @ Override     public int compareTo ( Country country ) {         return ( this . countryId < country . countryId ) ? - 1 : ( this . countryId > country . countryId ) ? 1 : 0 ; } } If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class. Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface. Comparator interface: Class whose objects to be sorted do not need to implement this interface.Some third class can implemen

.