This is a small code snippet and what I call an “IntervalMap”.
Basicly what it does is mapping an interval onto a value. For example

[0,5) → object1
[5,10) → object2

The idea is that if you give a key that is in one of the intervals that you get the object associated with that interval

For example:
‘3’ will be mapped on object1

public class IntervalMap<K extends Comparable<K>, V> extends
TreeMap<K, V> {

V defaultValue = null;

public IntervalMap(V defaultValue) {
    super();
    this.defaultValue = defaultValue;
}

/**
*
* Get the value corresponding to the given key
*
* @param key
* @return The value corresponding to the largest key 'k' so that
*         " k is the largest value while being smaller than 'key' "
*/
public V getValue(K key) {

    // if it is equal to a key in the map, we can already return the
    // result
    if (containsKey(key))
        return super.get(key);

    // Find largest key 'k' so that
    // " k is the largest value while being smaller than 'key' "

    // highest key
    K k = lastKey();

    while (k.compareTo(key) != -1) {

        k = lowerKey(k);

        if (k == null)
            return defaultValue;
    }

    return super.get(k);

    }

    @Override
    public V get(Object key) {
        return getValue((K) key);
    }
}

In code:

IntervalMap<Integer, String> map = new InterValMap<Integer,String>(null);

map.put(0,”interval 1”)
map.put(5,”interval 2”);

System.out.println(map.get(3));
//output: “interval 1”
System.out.println(map.get(5));
//output: “interval 2”

If you want to put a maximum limit on it you should add a value (like null) that you can detect as invalid. The default value you have to set in the constructor is only returned if a key is given that is under the minimum key value in the intervalmap. In this case everything smaller than zero
.

//upper limit [10,+oo)
map.put(10,null);

If you have ideas on improving this code snippet. Or if you like it :-)
Please let me know in the comments below!

About these ads