Skip to main content

Replace HashTable with Map


While I was reviewing a code, I noted that there is a Sonar violation saying not to use HashTable. Which is correct. Also it suggested to use something like HashMap instead of HashTable.

I reached out the developer and asked to remove the HashTable but she said that use of HashMap did not work. Also when I asked why did you use HashTable at first place, the answer was legacy code expects it, hence for new code we need to add HashTable.

Let's see how we can solve such cases. 


First of all we need to understand why these kind of rules exists. Our codebase is very old hence we have lots of deprecated class usages. Former developers have used whatever the API available those days.
As a junior developer you need to understand, learn that classes like HashTable, Vector should not use in modern codes because those are synchronized. You need to replace those with modern APIs.
Hashtable<Integer, String> ht1 = new Hashtable<>();

Problem... Again

One of those basic good practices in software development is coding to abstractions. You might not see those good practices in old codes. Then why do you do the same? Perhaps, you also do not know it. Learn!

What can we do?

When you are working on a new code, always try to clean the legacy. Always leave the codebase healthier than when you found it (clean code).
With that in mind, you might think of possible abstractions you can use. Sonar/IDEA solution is wrong in this case as HashMap is a concrete class. The abstraction you can use/try for HashTable is Map which is an interface. If it is a Vector, you can use List. You may or may not generify it but still you have cleaned for a better code.
Map<Integer, String> ht1 = new Hashtable<>();

What you should not do

Do not violate basic OOP principles. Instead always try to adhere to them.
Do not write codes to match the legacy. Instead change the legacy. (not always possible. agree!)
Make the code better than what you found.


The code we write today is tomorrow's legacy code. Make future developers lives easier. Do not introduce new technical debt.

Happy coding