1/9/2024 0 Comments Check if key in hashmap java![]() ![]() The biggest advantage of using an API method is that it has already been tried and tested by many programmers and faced many inputs and conditions which is impossible for your own code to execute. The great Java programmer Joshua Bloch even included a chapter on this on his all-time great Java book Effective Java, a must-read book for any Java programmer. That's why it's always better to write extensive JUnit tests for your code to test positive, negative, and boundary conditions.Īnother suggestion I want to make is that it's always better to use an API method if it can do the job, not just me but many greats have also advised this. Many Java programmers will test this code for some valid input and think that it's working fine, only to create a subtle bug in production. This code is fragile, it will not work if you have added null values into HashMap because HashMap does allow null values. ![]() This is supposed to be easy, right? Yes, it is easy if you know JDK API well, all you need to is call the containsKey() method, it returns true if the given key exists in HashMap, otherwise false but I have seen many programmers write code like below which is not correct, which inspired me to write this blog post. package Java programmers, if you have working in Java programming language or writing server side programs then you may know that one of the common programming tasks while using HashMap in Java is to check if a given key exists in the map or not. From the main method we put a check if the HashMap contains a key before we retrieve the contents, if the key is not on the database we print a “Not found” message on the console. The HashMap returned by the init() method is having an Integer object as key and String object as values. From the example below, basically we have a method init() which actually do the assignment of values to the HashMap object which are expected to be returned by this method. This java example source code demonstrates the use of containsKey() method of HashMap class. The containsKey(Object key) method returns true if this map contains a mapping for the specified key. The key where which we want check if the HashMap contains it Public boolean containsKey(Object key) Parameter Input :
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |