gpt4 book ai didi

java - 整数区间内的哈希表键

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:05 24 4
gpt4 key购买 nike

我不知道这是否可行,但我正在尝试制作一个哈希表,其中 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

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

如果这可能,有什么想法吗?

谢谢

最佳答案

无需重新发明轮子,使用 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());

输出:

Cry Baby
School Time
Got a car yet?

关于java - 整数区间内的哈希表键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11188795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com