I need to create a map which will cache results of a third party lookup service. The request is made up of two objects for example, time
and month
. The map needs to map between (time, month)
and a result.
My initial idea is to make an object to wrap time
and month
into effectively a tuple object, so the cache is a map between this object and the result.
Is there a better way of doing this, without needing to wrap the request into the tuple object each time we need to use the cache?
Many thanks.
My initial idea is to make an object to wrap
time
andmonth
into effectively a tuple object
That's the right idea. Override hashCode()
and equals(Object)
of your tuple to make it work with HashMap<TimeMonthTuple>
, or compareTo(TimeMonthTuple)
to make it work with TreeMap<TimeMonthTuple>
Is there a better way of doing this?
This is the most straightforward way, unless you have a class that can replace TimeMonthTuple
with something that makes sense. For example, time and date could be combined into a Date
object.
In certain cases you could make a key based on a primitive wrapper. For example, if time
is expressed as the number of minutes since midnight and month
is a number between 1 and 12, inclusive, you could wrap both values into an Integer
, and use it as a key:
Integer makeTimeMonthKey(int time, int month) {
return (time * 12) + (month - 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With