I have a range of objects which needs to be ordered with a rule. But I need to be able to switch the rules however I have a limited set of ordering rules. Which data structure would be the best choice for that?
As an example I have this class:
class Test {
public final int amount;
public final int cost;
public final String name;
public final int whatever;
// ...
// TODO: add a constructor to set the fields :-)
}
How can I store those fields to order them by amount, cost, name or whatever. But just one of that rules.
I could imagine to use an ArrayList or a HashSet where I call the sort function with a custom Comparator. But I cannot imagine that this is efficiency. I think this is important on a mobile device. What is a better way to achieve that?
You can not use an
Setfor sorting, as it does not have any order. How every the concept of havingListand customComparator<T>is reasonable.You should go with that solution and do not care about performance at this point. If you will be not satisfied from gained result then try to came up with better solution.
The best solution is reading data from storage in proper order. I do not know how your app store that structure. Therefore I can not help you with that. But implement the comparable solution and you will see that is not so bad.
What is important on mobile device is memory usage. If your application will use lot of those sorting operation you could create the Comparators as enums so they will be loaded only once and in addition can simplify the code