RAND(0,N)

Good Old HashMap


Posted on 26 January 2022, by Kevin Mora



When I was working with certain code, I created a bug in the codebase, which utilized more memory and time than allowed.

I was asked to create a method/function able to iterate over the key-value pairs of a hash-map. For this, I decided to build a list of the keys, and a list of the values. Then, I would iterate over the list of keys – reasonable enough so far!

To get the value that corresponded to a key, I made the mistake of iterating over the list of keys again to find the current index of the key, getting the value at that index. I did this every time I wanted to access a value, so the key list was scanned for no reason two or three extra times for each key, which ended up consuming more resources and could have potentially caused a bigger problem.


public void UpdateArticlesInCart() {
        HashMap<Article, Integer> content = cart.outerMap();
        List<Article> l = new ArrayList<>(content.keySet());
        List<Integer> k = new ArrayList<>(content.values());
        List<String> output = new LinkedList<>();
        for(Article a : l) {
            if(k.get(l.indexOf(a)) == 1) {
                output.add(k.get(l.indexOf(a)) + "some text");
            } else {
                output.add(k.get(l.indexOf(a)) + "some other text");
            }
        }
        ItemList.setItems(FXCollections.observableList(output));
} 

After debugging the code I realize what I just described. It was easy to solve, but I found this bug very interesting because it clearly shows how compilers assume your code has no errors as long as it is semantically and syntactically correct – it does not contemplate things like time or memory complexity, which is certainly a scary thing when you are dealing with thousands of lines of code.

It could have just been a simple iteration over a map, but my lack of atention increased the complexity , which is not terrible, but it's definitely not close to good.