Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make 2 comparable methods in only one class?

I've got one class, that I sort it already by one attribute. Now I need to make another thing, that I need to create another way to sort my data. How can I make it, so I can choose between the two methods. The only command I know is Collections.sort that will pick up the method compareTo from the class I want to compare its data.

Is it even possible?

like image 658
Gondim Avatar asked Dec 13 '10 19:12

Gondim


People also ask

Can you have two compareTo methods?

No you cannot, but you can create a separate Comparator for each ordering.

How does Comparable affect original class?

Comparable affects the original class i.e. actual class is modified. Comparator doesn't affect the original class i.e. actual class is not modified. Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.

What is comparable Sorting?

In Java, we can implement whatever sorting algorithm we want with any type. Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers. The Comparator interface allows us to do the same but in a more flexible way.


1 Answers

What you need to do is implement a custom Comparator. And then use:

Collections.sort(yourList, new CustomComparator<YourClass>()); 

Specifically, you could write: (This will create an Anonymous class that implements Comparator.)

Collections.sort(yourList, new Comparator<YourClass>(){     public int compare(YourClass one, YourClass two) {         // compare using whichever properties of ListType you need     } }); 

You could build these into your class if you like:

class YourClass {      static Comparator<YourClass> getAttribute1Comparator() {         return new Comparator<YourClass>() {             // compare using attribute 1         };     }      static Comparator<YourClass> getAttribute2Comparator() {         return new Comparator<YourClass>() {             // compare using attribute 2         };     } } 

It could be used like so:

Collections.sort(yourList, YourClass.getAttribute2Comparator()); 
like image 183
jjnguy Avatar answered Sep 21 '22 17:09

jjnguy