Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Best collection for small number of key value pairs

I'm currently creating a prototype of a Rock, Paper Scissors program and I need to store the selections in an Integer/String format.

What would be the "best" collection to use, in terms of speed of searching and memory usage? The premise being that the computer will pick a random number, then the key value pairs are searched to find the appropriate selection name for use later in the program

EDIT:

To clarify, there will be at most 5 key value pairs in the collection, with integers as the keys

further clarification based on comments. Im looking for a key/value collection for a small amount of pairs (5 at most)

like image 996
jbailie1991 Avatar asked Aug 19 '14 12:08

jbailie1991


3 Answers

An ArrayList or an HashMap would be fine if your keys are Integer.

Both are O(1) and expect unique keys.

Otherwise, if they are String, HashMap only would fit.

like image 183
Mik378 Avatar answered Oct 22 '22 05:10

Mik378


HashMap would be the best one. get() has O(1) time complexity . O(1) means independent of the number of elements i.e, constant.

like image 38
TheLostMind Avatar answered Oct 22 '22 05:10

TheLostMind


If you need a Map and you do not need a SortedMap, HashMap is almost always the right choice.

Note that one of the constructors of HashMap has an argument telling it the initial size of the map. The constructor will use that to allocate a reasonable amount of memory for the map, which is helpful if the size of your map is likely to be smaller than the default size (which is 16).

like image 35
Raedwald Avatar answered Oct 22 '22 05:10

Raedwald