I understand that a queue is a collection type that is accessed through the head and/or tail.
I also understand that a map is a collection type the contains a number of unique keys, which each have开发者_JAVA技巧 an associated value.
What I need, is a map, with a fixed number of values, where the keys will be set once, and will not be changed after they are first set.
The hard part I can't get my head around is getting the values to act as a queue with a fixed length, which can be pushed, without affecting the key.
For example:
Initial collection (newest items at the top):
Key1, Value1
Key2, Value2
Key3, Value3
Collection after adding new value NewValue:
Key1, NewValue
Key2, Value1
Key3, Value2
So, I want the key to stay the same, and be able to add the new value, by pushing the oldest value off the end, and moving all other values further down towards the end.
If a type like this isn't available within the framework, could somebody please recommend a way to implement it.
Thank you!
EDIT: An example of why I need to do this:
I need to be able to access the values according to the time period it was created in.
Example:Key: 0 will contain a value from today
Key: -1 will contain a value from yesterday Key: -2 will contain a value from two days ago etc.Only one value will be entered every day, and one value will ALWAYS be entered every day.
Sounds like you could use:
new LinkedHashMap<Long,V>(initialCapacity, loadFactor, false) {
protected boolean removeEldestEntry(Map.Entry<Long,V> e) {
return size() > MAX_ENTRIES;
}
};
To get or put items in this map you will need to canonicalize your timestamp, e.g., to 00:00:00.000 of the day.
An advantage of this approach is when the assumption that "one value will ALWAYS be entered every day" is violated it won't fail silently.
So, you're really talking about an index into an array.
I'd just wrap an 'ArrayList` in your object.
Your push
method would also remove the "oldest" element from the end. You'd define methods such as getToday()
and getPriorDay(numDaysBackFromToday)
However, you're using a lot of magic numbers there if you're not actually storing a date or a time with the data. You're hoping that the data has been loaded correctly.
Personally I'd use a timestamp associated with the data in a LinkedHashMap
and iterate to find the one you want.
I've rethought my question with regards to the magic numbers, and have decided it'd be easier to use a predefined collection type with positive indexes. Then I'll simply make the push method drop the last item off the end when I reach the maximum number of values I need.
Then I'll get my class to interpret -1 as 1 to get the required value.
Thanks for your help, I was simply over-thinking things.
精彩评论