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?
What you need to do is implement a custom
Comparator
. And then use:Specifically, you could write: (This will create an Anonymous class that implements
Comparator
.)You could build these into your class if you like:
It could be used like so:
You can only have one
compareTo()
method in your class.If you want to sort the same class more than one way, create
Comparator
implementations.If the two methods require the exact same footprint, you may be inappropriately overloading a single class with multiple uses, which would be resolved by fixing your class hierarchy - like instead of using "shape", subclass it with "oval", "rectangle", etc.
If subclassing doesn't make sense, you need to create different comparison classes. In Java, you often use a Comparator for comparisons. Create several (or create a configurable comparator): IsbnComparator, AuthorComparator, etc.
Oh, and the configurable option would be: