使用时间概念实现地图

问题描述

我最近遇到了使用以下两种方法实现数据结构的挑战:

set(key,value,time):在指定时间设置键值。
get(key,time):在指定时间或更早的时间获取key的值。

如果我们在特定时间设置一个键,它将永远保持该值或直到它在以后设置为止。

示例

示例 1

d.set(1,1,0) // set key 1 to value 1 at time 0
d.set(1,2,2) // set key 1 to value 2 at time 2
d.get(1,1) // get key 1 at time 1 should be 1
d.get(1,3) // get key 1 at time 3 should be 2

示例 2

d.set(1,5) // set key 1 to value 1 at time 5
d.get(1,0) // get key 1 at time 0 should be null
d.get(1,10) // get key 1 at time 10 should be 1

示例 3

d.set(1,0) // set key 1 to value 2 at time 0
d.get(1,0) // get key 1 at time 0 should be 2

解决方法

这是我的实现:


import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

/**
 * An Implementation a Map with the notion of Time.
 *
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 * @param <T> the type of time tracked by this map.
 *            T MUST implement {@link Comparable} to have a notion of comparing times.
 * @author Hari Krishnan
 * @see Map
 * @see NavigableMap
 */
public class TimedMap<K,V,T extends Comparable<T>> {

    private final Map<K,NavigableMap<T,V>> map = new HashMap<>();

    /**
     * Associates the specified value with the specified key at the specified time in this map.
     * If the map previously contained a mapping for the key at this time,* the old value is replaced by the specified value.
     *
     * @param key   key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @param time  time at which said association should occur
     */
    public void set(K key,V value,T time) {
        if (!map.containsKey(key))
            map.put(key,new TreeMap<>());
        map.get(key).put(time,value);
    }

    /**
     * Returns the value to which the specified key is mapped at the specified time or earlier,* or {@code null} if this map contains no mapping for the key at the specified time or earlier.
     *
     * @param key  the key whose associated value is to be returned
     * @param time the time(or earlier) at which the values associated with the key is to be returned.
     * @return The value to which the specified key is mapped at the specified time or earlier,or
     * {@code null} if this map contains no mapping for the key at the specified time or earlier.
     */
    public V get(K key,T time) {
        try {
            return map.get(key).floorEntry(time).getValue();
        } catch (NullPointerException ex) {
            return null;
        }
    }

}

欢迎改进和建议!