Organizational Research By

Surprising Reserch Topic

when to use comparable and comparator


when to use comparable and comparator  using -'java,comparator,comparable'

I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works.

Now looking back at this, I am wondering if I should have instead have the my class implement Comparable instead of creating a new class that implements Comparator. The score is the only field that the objects will be ordered on.


What I have done acceptable as a practice?
Is the right approach "First have the class implement Comparable (for the natural ordering) and if an alternative field comparison is required, then create a new class that implements Comparator" ?
If (2) above is true, then does it mean that one should implement Comparator only after they have the class implement Comparable? (Assuming I own the original class).

    

asked Oct 7, 2015 by ajit.chavhan
0 votes
11 views



Related Hot Questions

15 Answers

0 votes
NULL
answered Oct 7, 2015 by kotmus2002
0 votes
NULL
answered Oct 7, 2015 by dhananjayksharma
0 votes
NULL
answered Oct 7, 2015 by virendra.bajaj
0 votes
NULL
answered Oct 7, 2015 by rolvyrf
0 votes
NULL
answered Oct 7, 2015 by rajesh
0 votes
NULL
answered Oct 7, 2015 by shikhar jain
0 votes
NULL
answered Oct 7, 2015 by suyesh.lokhande
0 votes
NULL
answered Oct 7, 2015 by deepak
0 votes
NULL
answered Oct 7, 2015 by abhi
0 votes
NULL
answered Oct 7, 2015 by okesh.badhiye
0 votes
NULL
answered Oct 7, 2015 by akhilesh
0 votes
NULL
answered Oct 7, 2015 by rajeevr642
0 votes
NULL
answered Oct 7, 2015 by bhavin
0 votes
NULL
answered Oct 7, 2015 by mtabakade
0 votes
NULL
answered Oct 7, 2015 by vijayshukla80

...