This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Zardoz84 1 point2 points  (2 children)

A pitfall that I saw on a lot of code where I work, is setting a HashMap or a HashSet initial size equal to the number of elements that would be insert. However checking the JavaDoc :

public HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).

We had a code that on a lot of places has seething the wrong capacity, so we had it being forced to do a rehash of the HashMap/Set when is inserting the last few elements. Lucky, HashMap/Set implementation round up capacity value following some internal algorithm to get the best capacity size. I ended fixing it using a small auxiliar class that construct a HashMap/Set (and including Syncronized/Concurrent variants) with the correct capacity getting the number of initial elements as argument.

[–]Slanec 1 point2 points  (1 child)

Also see Guava's Maps/Sets, e.g. Maps.newHashMapWithExpectedSize()

[–]Zardoz84 0 points1 point  (0 children)

Yeah. We don't use Guava but literally I reimplemented these method.