我有一系列需要按照规则排序的对象。但我需要能够随时更改规则,然而,我只有一组有限的排序规则。哪种数据结构是最好的选择?
例如,我有以下这个类:
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 :-)
}
我该如何存储这些字段以便按数量、成本、名称或其他方式对它们进行排序。但只能使用其中一种规则。
我可以想象使用ArrayList
或HashSet
,在其中使用自定义的Comparator
函数调用sort函数来实现。但我认为这样做效率不高,特别是在移动设备上。有更好的方法来实现吗?