我有一个对象如下:
public class Record{
Int ID;
String title;
Date date;
Duration time;
public Record createRecord(int ID, String title, Date date, Duration time){
this.ID= ID;
this.title = title;
this.date = date;
this.time = time;
return this;
}
}
我将多个对象存储在一个列表中。插入新记录时,我需要检查列表中是否已经有一个仅具有相同标题和日期的对象,并替换其中的时间。
我正在寻找任何可以实现 O(1) 时间的解决方案。
最佳答案
在 ArrayList 中搜索现有元素将花费 O(n),如果 ArrayList 已排序(例如,您维护已排序的记录),则需要 O(logn) 时间。因此,为了实现所需的功能,我将使用 Map 结构,按标题索引,然后按日期索引。像这样:
// Create general records DB
Map<String, Map<Date, Record>> records = new HashMap<>();
// Create sub DB for records with same ID
Map<Date, Record> subRecords = new HashMap<>();
// Assuming you've got from somewhere id, title and rest of the parameters
subRecords.put(recordDate, new Record(id, title, time, duration));
records.put(recordId, subRecords)
// Now checking and updating records as simple as
sub = records.get(someTitle); // Assuming you've got someTitle
if (sub != null) {
record = sub.get(someDate); // Same for someDate
if (record != null) {
record.updateTime(newTime);
}
}
使用 Map of Map 将避免您需要覆盖 equals 和 hashCode 方法,而我同意 Map<String, Map<Date, Record>>
可能看起来有点花哨或奇怪。 While 将为您提供在 O(1) 时间内更新记录或检查是否存在的能力。额外的好处是您不需要创建记录来检查是否存在或更新,您可以直接使用标题和日期来检索您需要的内容。
关于java - 比较 ArrayList Java 中的部分对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46290917/