使用 arrayList 中的两个键进行搜索
我想对对象的 ArrayList 实现快速搜索。这些对象由 int oldId、int newId 和 int inList 等组成。
现在,我尝试使用列表上的 Collections.binarySearch 实现二分搜索,但问题是我需要使用 oldId 和 inList 进行搜索,以从相应的对象中获取 newId。示例:我有 oldId = 9 和 inList = 1,并尝试获取已在其他地方分配的 newId。本质上是映射 oldId-newId 并将它们分组。可能存在重复的 oldId,但它们必须位于不同的列表中,并且具有唯一的 newId。
您认为对这些映射对象使用哈希映射会更好吗?或者,是否有解决方案(可能是对象的比较器)从 oldId 和 inList 信息中获取 newId 。我也在寻找一种快速搜索算法。
非常感谢您的帮助,我很欣赏想法。
这是我为二分搜索编写的比较器,但是我不知道如何在此处添加 inList 信息。
公共类CompareTermId实现比较器
{
public CompareTermId(){}
public int compare(MObj a, MObj b){
if(a.oldTermId < b.oldTermId) return 1;
else if(a.oldTermId > b.oldTermId) return -1;
else return 0;
}
}
I would like to implement a fast search on an ArrayList of objects. These objects consist of an int oldId, int newId and int inList, among with other things.
Now, I tried implementing a binary search using the Collections.binarySearch on my list, but the problem is I need to search using the oldId and inList, to get the newId from the corresponding object. Example: I have oldId = 9 and inList = 1, and try to get the newId that has been assigned somewhere else. Essentially mapped the oldId-newId's and grouped them. There may be duplicate oldId's but they must be in different lists, and have unique newIds.
Do you think it would be better to use a hashmap for these map objects? Or else, is there a solution (maybe a comparator for the objects) to get the newId's from the oldId and inList info. I am also looking for a fast search algorithm.
Thanks a lot for helps, I appreciate ideas.
Here is a comparator I have written for the binary search, however I couldn't figure out how to add the inList info here.
public class CompareTermId implements Comparator
<MObj>
{
public CompareTermId(){}
public int compare(MObj a, MObj b){
if(a.oldTermId < b.oldTermId) return 1;
else if(a.oldTermId > b.oldTermId) return -1;
else return 0;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如您所邀请的,我将推荐 HashMap :)
原因是因为 HashMap 为单个键提供了有效的恒定时间查找。
如果您按如下方式构建哈希图:
然后填充它:
然后您可以按如下方式查找:
As you have invited I am going to recommend HashMap :)
The reason is because HashMap provides effectively constant time lookups for a single key.
If you construct a hash map as follows:
And then populate it:
Then you can lookup as follows:
我认为最好将它们全部封装到一个类中,并使用 List 和 Comparator 来查找它们。
I think it'd be better to encapsulate all of it into a single class and use List and Comparator to find them.
如果你让你的比较器看起来像这样:
你应该是黄金,即使使用二进制搜索方法。该比较器将首先按其 oldTermId 然后按其 inList 值对项目进行排序,以便具有相同 oldID 和不同 inList 值的两个项目被视为不同。
If you make your comparator look like this:
You should be golden, even for using the binarySearch methods. This comparator will sort items first by their oldTermId and then by their inList value, so that two items with the same oldID and different inList values are regarded as different.