整数区间内的Hashtable键

xla*_*8or 11 java hashtable

我不知道这是否可行,但我正在尝试制作一个Hashtable,其中Interval是一个具有2个整数/长值,开始和结束的类,我想做这样的事情:

Hashtable<Interval, WhateverObject> test = new Hashtable<Interval, WhateverObject>();
test.put(new Interval(100, 200), new WhateverObject());
test.get(new Interval(150, 150)) // returns the new WhateverObject i created above because 150 is betwwen 100 and 200
test.get(new Interval(250, 250)) // doesn't find the value because there is no key that contains 250 in it's interval
Run Code Online (Sandbox Code Playgroud)

基本上我想要的是Interval对象中一系列值之间的键给出对应的WhateverObject.我知道我必须在区间对象中重写equals()和hashcode(),我认为主要问题是以某种方式将所有值介于100和200之间(在此特定示例中)以给出相同的散列.

任何想法,如果这是可能的?

谢谢

Sea*_*oyd 14

不需要重新发明轮子,使用一个NavigableMap.示例代码:

final NavigableMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(0, "Cry Baby");
map.put(6, "School Time");
map.put(16, "Got a car yet?");
map.put(21, "Tequila anyone?");
map.put(45, "Time to buy a corvette");

System.out.println(map.floorEntry(3).getValue());
System.out.println(map.floorEntry(10).getValue());
System.out.println(map.floorEntry(18).getValue());
Run Code Online (Sandbox Code Playgroud)

输出:

Cry Baby
School Time
有车吗?

  • @aaronburro它会工作,只要你为"洞"插入空值(并添加更多的客户端代码) (2认同)