I had originally written an ArrayList
and stored unique values (usernames, i.e. Strings
) in it. I later needed to use the ArrayList
to search if a user existed in it. That's O(n)
for the search.
My tech lead wanted me to change that to a HashMap
and store the usernames as keys in the array and values as empty Strings
.
So, in Java -
hashmap.put("johndoe","");
I can see if this user exists later by running -
hashmap.containsKey("johndoe");
This is O(1)
right?
My lead said this was a more efficient way to do this and it made sense to me, but it just seemed a bit off to put null/empty as values in the hashmap and store elements in it as keys.
My question is, is this a good approach? The efficiency beats ArrayList#contains
or an array search in general. It works.
My worry is, I haven't seen anyone else do this after a search. I may be missing an obvious issue somewhere but I can't see it.