【发布时间】:2019-06-20 10:50:26
【问题描述】:
我正在维护对象的排序 ArrayList(通过覆盖 here 所示的 add 方法),其中每个对象具有 2 个属性:a 和 b。如何检索 a 等于 5 的对象?
我不能使用地图,因为我要对列表进行排序的值必须能够接受重复项(这就是为什么this answer 在这里不适用)。
代码:
class TimeMap {
List<MyType> list = new ArrayList<KVT>() {
public boolean add(KVT mt) {
int index = Collections.binarySearch(this, mt, new SortByTime());
if (index < 0) index = ~index;
super.add(index, mt);
return true;
}
};
}
class KVT{//value-timestamp object
String value;
int timestamp;
public VT(String v, int t){
value=v;
timestamp=t;
}
}
class SortByTimestamp implements Comparator<KVT>{
public int compare(KVT a, KVT b){
return a.timestamp.compareTo(b.timestamp);
}
}
【问题讨论】:
-
为什么不把你写的代码贴出来?
-
你需要遍历列表进行线性搜索