整数区间内的Hashtable键 [英] Hashtable key within integer interval

查看:128
本文介绍了整数区间内的Hashtable键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't know if this is possible but i'm trying to make an Hashtable of where Interval is a class with 2 integer / long values, a start and an end and i wanted to make something like this:

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

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

So basically what i want is that a key between a range of values in an Interval object give the correspondent WhateverObject. I know i have to override equals() and hashcode() in the interval object, the main problem i think is to somehow have all the values between 100 and 200 (in this specific example) to give the same hash.

任何想法,如果可能的话?

Any ideias if this is possible?

谢谢

推荐答案

无需重新发明轮子,请使用 的NavigableMap 。示例代码:

No need to reinvent the wheel, use a NavigableMap. Example Code:

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());

输出:


Cry Baby

学校时间

有车吗?

Cry Baby
School Time
Got a car yet?

这篇关于整数区间内的Hashtable键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆