简体   繁体   中英

Java speed comparison between HashMap and ArrayList

I wonder if there are any comparison between searching elements in Hashmap vs ArrayList. The case which I encountered looks as follow: I'll have small amount of elements (usually 4-6 probably up to 10). I've integer Id of such element and I'll get a lot of calls which will search elements using id and execute some method on this element. It looks like good usecase for hashmap however I started to wonder if linear collection like ArrayList wouldn't be better here. For example because of CPU cache. And also to use search on map I need autoboxing to create Integer from primitive. Question is for this case better is do linear search and comparison of primitive ints or rather stick to hashmap?

如果您的 id 不是基于索引的,那么 ArrayList#get 将是O(n) (您必须遍历元素)而 HashMap#get 将是O(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM