I have an Object as follows:
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;
}
}
I am storing multiple objects in a List. While inserting a new record, I need to check if the list already has an object with ONLY the same title and date, and replace the time in it.
I am looking for any solution which can achieve O(1) time.
Searching in ArrayList for existing element will take you O(n) in case of sorted ArrayList (e.g. you maintain records sorted) it will require O(logn) time. Therefore to achieve desired functionality I'd use Map structure, indexing by title and then by date. Something like this:
Using Map of Map will prevent from you the need to override equals and hashCode methods, while I'd agree that
Map<String, Map<Date, Record>>
might look a bit fancy or weird. While will provide you with ability to update the records or check for existence within O(1) time. Additional nit is that you do not need to create a record to check for existence or for update, you can directly use Title and Date to retrieve what you needed.