1

I'm working on a Minecraft PvP mod and want to use a hashmap to store each player's name with their team. Their would be a total of 64 players in a match and only 1 match on the server at a time.

Do I need to use a hashmap that is 64 slots? In the past I have had a very bad time understanding how hashmaps work , I'm starting to get it now.

pratim_b
  • 1,160
  • 10
  • 29
  • A past question talks about the ideal initial size and load factor of a hashmap. Hope this helps http://stackoverflow.com/questions/7115445/what-is-the-optimal-capacity-and-load-factor-for-a-fixed-size-hashmap – AurA Feb 17 '14 at 06:27
  • 1
    you might want to use the key as the team name , and the value is an array / arraylist that holds the players – Exorcismus Feb 17 '14 at 06:27

3 Answers3

3

No, the HashMap will increase in size automatically to keep its load factor under the default of 0.75 if you don't specify anything. Even if you don't do anything explicitly about it, your HashMap will grow as you populate it, while keeping appropriately small if you don't use all 64 entries.

The reason you'd want to specify in initial capacity is really just if you know in advance that you're going to fill it with at least that many entries, so that it won't have to rehash and reallocate while you're filling it up.

In short: If you just leave HashMap to its defaults, it's usually alright. :)

Dolda2000
  • 25,216
  • 4
  • 51
  • 92
1

In Java the default load factor is 0.75 and the default initial capacity of a hash map is 16.

The initial set of values for hashmap are as under :

DEFAULT_INITIAL_CAPACITY = 16; 
DEFAULT_LOAD_FACTOR = 0.75; 
THRESHOLD = DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR;

The hash map will automatically rehash the contents of the hash map into a new array with a larger capacity. This happens when the number of data in the hash map exceeds the THRESHOLD. Each resize leads to a doubled capacity 16*0.75, 32*0.75, 64*0.75.

In simple terms you should initialize it to something like

int capacity = (int) ((your_data)/0.75+1);
HashMap<String, Integer> myHashMap = new HashMap<String, Integer>(capacity);

In your case your_data = 64

Also, you can simply instantiate the default hashmap and it always resizes itself but it does not give as good performance as you initializing it properly.

You can read a previous post regarding the same Best way to initialize a HashMap

Community
  • 1
  • 1
AurA
  • 12,135
  • 7
  • 46
  • 63
0

Having 64 slots increases the possibility of collisions because it's quite likely that multiple keys will map to the same slot. Better to use the standard HashMap. Or, if you're really concerned about space, you could also use a data structure such as a binary tree and alphabetize the players' names, including the team name in the Node. Binary tree lookup is a larger order of magnitude than HashMap lookup, but still very fast.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64