使用 Collections.binarySearch 检索对象
我声明了一个带有 id、Name、age、contactNumber 和 Address 属性的 POJO 类。我声明了所有 getter 和 setter。现在我正在使用 HashMap
。默认情况下,我按 Name
属性对这些值进行排序。现在我的需要是通过 id 搜索一个对象,并且该方法应该返回一个对象(该对象作为值存储在 HashMap 中)。那么我如何使用Collections.binarySearch()
来满足这个要求。
I declared a POJO class with id, Name, age, contactNumber and Address
attributes. I declared all getters and setters. Now I am using HashMap<String, POJO_CLASS>
. By default I sorts these values by Name
attribute. Now my need is to search an object by id, and that method should return an object (which is stored in HashMap as value). So how can I use Collections.binarySearch()
for this requirement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
500 个对象并不算多,所以我只是将它们放入第二个以 id 为键的 HashMap 中。
500 objects is not that many, so I would just put them in a second HashMap keyed on the id.
更好的问题是你为什么想要这样做。 HashMap 查找速度非常快,为 O(1) 时间,而在具有随机访问能力的列表(ArrayList)上二分搜索将花费 O(lg(N)) 时间。
如果您确实想要使用二分搜索,那么您需要将对象存储在列表中(可能是ArrayList)并对该列表进行排序,然后调用
Collections.binarySearch(list, value).
The better question is why would you want to. HashMap lookups are going to be very fast, O(1) time whereas binary searches are going to take O(lg(N)) time on Lists that have random access abilities (ArrayList).
If you really want to use binary searches then you need to store your objects in a list (ArrayList probably) and have that list sorted and then call
Collections.binarySearch(list, value)
.如果您需要按名称和 ID 进行快速查找,则需要将 POJO 永久存储在两个不同的数据结构中。在这种情况下,根据 id 构建第二个 HashMap 将为您提供最佳性能。
如果地图不是那么大或者通过 id 查找的情况相对较少,这可能会不必要地复杂。在这种情况下,我只会通过 HashMap 进行线性搜索。
If you need fast lookup by both name and by id, you're going to need to permanently store the POJOs in two different data structures. In this case, building a second HashMap off of id, would give you the best performance.
This may be unnecesarily complex if the map is not that large or lookup by id is a relatively infrequent occurance. In that case I would just do a linear search through the HashMap.