0

Possible Duplicate:
Memory overhead of Java HashMap compared to ArrayList

I try to search on google but didnt found an answer, I need to store 160 entrys on a collection, and I dont want to iterate over them, I want to get the value by one entry, a point 2D, what is the best? With less memory consume and faster access ? Thanks alot in advance ;)

Community
  • 1
  • 1
TiagoM
  • 187
  • 3
  • 14

3 Answers3

5

For 160 entries? Who cares. Use whichever API is better for this – probably the HashMap.

Also, with data structures, very frequently the tradeoff is speed versus memory use – as a rule you can't have both. (E.g. a hash table that uses chaining for collision resolution will have memory overhead for the buckets over an array; accessing an element by key in it will be faster than searching the array for the key.)

millimoose
  • 39,073
  • 9
  • 82
  • 134
  • okay thanks alot, and its kinda bad to rehash ? because I dont have sure if it will be 160.. or 140.. or 130.. it will be some value between 100 and 160 of entrys.. – TiagoM Apr 02 '12 at 12:27
  • Rehashing isn't great for performance, but how bad depends on the lifetime of the Map. If the Map is long-lived, and there'll be many reads after it reaches its final capacity, it probably doesn't matter. And you can prevent resizing the Map if you can set a reasonable upper bound on the required capacity - in your case, it's 160 elements, so you can just create the maps with that many buckets using the constructor for that: http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#HashMap(int) – millimoose Apr 02 '12 at 17:17
2

If Hashmap vs ArrayList are you only two options, obviously it is going to be a Hashmap for speed of retrival. I am not sure of memory usage. But ArrayList has the ability to maintain order.

Churk
  • 4,556
  • 5
  • 22
  • 37
2

With less memory consume and faster access ?

HashMap probably gives faster access. This could be computationally important, but only if the application does a huge number of lookups using the collection.

ArrayList probably gives least memory usage. However, for a single collection containing 160 elements, the difference is probably irrelevant.


My advice is to not spend a lot of time trying to decide which is best. Toss a coin if you need to, and then move on to more important problems. You only should be worrying about this kind of thing (where the collection is always small) if CPU and/or memory profiling tells you that this data structure is a critical bottleneck.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216