UPDATE:加全面实施
更新2:如果你愿意,你可以使用RangeMap内部theMap
作为意见提出。
如果关键的范围没有重叠,您可以创建自定义容器与它实现Comparable
自定义密钥在内部TreeMap
存储数据:
class MyStorage<T> {
private static final class Range implements Comparable<Range> {
private int first;
private int last;
public Range(int first_, int last_) {
first = first_;
last = last_;
}
// This heavily relies on that the ranges don't overlap
@Override public int compareTo(Range other) {
if (last < other.first)
return -1;
if (first > other.last)
return 1;
return 0;
}
}
private Map<Range, T> theMap = new TreeMap<Range, T>();
public void put(String key, T obj) {
String[] ranges = key.split(";");
for (String range : ranges) {
//System.out.println("Adding " + range);
String[] bounds = range.split("-");
//System.out.println("Bounds " + bounds.length);
int first = Integer.parseInt(bounds[0]);
if (bounds.length == 1)
theMap.put(new Range(first, first), obj);
else
theMap.put(new Range(first, Integer.parseInt(bounds[1])), obj);
}
}
public T get(String key) {
return get(Integer.parseInt(key));
}
public T get(int key) {
return theMap.get(new Range(key, key));
}
}
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
MyStorage<Integer> storage = new MyStorage<Integer>();
storage.put("10;20-30", 123);
storage.put("15;31-50", 456);
System.out.println(storage.get("42"));
}
}
你可以实现一个自定义的数据结构,包装一个'Map',而不是覆盖'get'方法。 – 2014-08-29 07:26:26
如果一个对象有键,说'10-20',另一个有'15-25'键,那么应该返回什么? – 2014-08-29 07:31:53
在我的情况下,这是不可能的,“地图”是从硬编码的JSON文件启动时预填充。 – Niko 2014-08-29 07:32:31