开发者

Retrieve an object using 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 us开发者_开发百科e Collections.binarySearch() for this requirement.


500 objects is not that many, so I would just put them in a second HashMap keyed on the id.


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜