{"id":7678,"date":"2025-05-29T13:21:58","date_gmt":"2025-05-29T13:21:58","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=7678"},"modified":"2026-04-01T11:54:45","modified_gmt":"2026-04-01T11:54:45","slug":"java-hashtable","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-hashtable\/","title":{"rendered":"HashTable &#8211; Java data structures"},"content":{"rendered":"<p>Java HashTable is a data structure that allows you to safely work with data even in multi-threaded applications. Although it is an older but still reliable implementation, its use has specific characteristics. In the following lines, we&#8217;ll look at how the HashTable class works, what its advantages and limitations are, and also when it makes sense to use it instead of more modern alternatives such as HashMap.<\/p>\n<p>The <strong>HashTable<\/strong> class is one of the older Java implementations of hash tables.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-7592 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashTable-kolekcia-hierarchia-dedicnosti.webp\" alt=\"HashTable collection - inheritance hierarchy (source: media.geeksforgeeks.org\/wp-content\/uploads\/20201124183400\/HierarchyofHashtable.png)\" width=\"400\" height=\"313\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashTable-kolekcia-hierarchia-dedicnosti.webp 400w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashTable-kolekcia-hierarchia-dedicnosti-300x235.webp 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p><strong>HashTable<\/strong> <strong>collection &#8211; inheritance hierarchy <\/strong>(source: media.geeksforgeeks.org\/wp-content\/uploads\/20201124183400\/HierarchyofHashtable.png)<\/p>\n<div class=\"inside\"><\/div>\n<h2>HashTable in Java &#8211; data structure introduction<\/h2>\n<p>The <strong>HashTable<\/strong> class is an implementation of the <strong>Map<\/strong> interface that stores key-value pairs and uses a hash table for fast operations. Each key must be unique and can never be <em>null<\/em>, nor can the value, so null values are not allowed in HashTable.<\/p>\n<p>Unlike more modern collections like <a href=\"https:\/\/msgprogramator.sk\/en\/java-hashmap\/\">HashMap<\/a>, HashTable is synchronized, which means it is safe for use in multithreaded applications, but at the same time its operations can be slower.<\/p>\n<div class=\"article-sharing-card\"><a href=\"https:\/\/msgprogramator.sk\/en\/java-hashmap\/\" class=\"article-card\"\n        aria-label=\"HashMap &#8211; Java data structures\"><div class=\"article-card-wrap\"><div class=\"article-card-wrap-image\"><span class=\"article-category\">Java<\/span><span class=\"article-reading-time\">6 min.<\/span><img loading=\"lazy\" decoding=\"async\" width=\"954\" height=\"600\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashMap-\u2013-Java-datove-struktury954x600.webp\" class=\"img-fluid wp-post-image\" alt=\"Laptop with on-screen programming code\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashMap-\u2013-Java-datove-struktury954x600.webp 954w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashMap-\u2013-Java-datove-struktury954x600-300x189.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashMap-\u2013-Java-datove-struktury954x600-768x483.webp 768w\" sizes=\"auto, (max-width: 954px) 100vw, 954px\" \/><\/div><div class=\"article-wrap-content\"><div class=\"article-wrap-date\"><span class=\"article-date\">28. 5. 2025<\/span><\/div><h3 class=\"article-wrap-title\"><span href=\"https:\/\/msgprogramator.sk\/en\/java-hashmap\/\">HashMap &#8211; Java data structures<\/span><\/h3><div class=\"article-wrap-excerpt\">Learn about the HashMap data structure in Java - an overview of methods, operations, advantages, disadvantages and practical examples of its use.                <\/div><\/div><\/div><\/a><\/div>\n<p>HashTable uses the <em>hashCode()<\/em> method of objects to evenly divide pairs into internal \u201cbuckets\u201d. This allows to perform adding, searching and deleting operations in constant time (O(1)) with an ideal layout.<\/p>\n<h2>HashTable &#8211; constructors<\/h2>\n<p>To create a HashTable instance, we have several constructors available:<\/p>\n<p><strong>1. Empty HashTable<\/strong><\/p>\n<p>Creates an empty hash table with default capacity (11) and load factor (0.75).<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Hashtable&lt;Integer, String&gt; table = new Hashtable&lt;&gt;();<\/code><\/pre>\n<p><strong>2.HashTable with defined capacity<\/strong><\/p>\n<p>Creates a new, empty hash table with the specified initial capacity and default load factor (0.75).<\/p>\n<p><code class=\"language-java\" data-line=\"\">Hashtable&lt;Integer, String&gt; table = new Hashtable&lt;&gt;(20);<\/code><\/p>\n<p><strong>3. HashTable with defined capacity and load factor<\/strong><\/p>\n<p>Creates a new, empty hash table with the specified initial capacity and the specified load factor.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Hashtable&lt;Integer, String&gt; table = new Hashtable&lt;&gt;(20, 0.82f);<\/code><\/pre>\n<p><strong>4. HashTable constructed from Map<\/strong><\/p>\n<p>Creates a new hash table with the same mapping as the given Map.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Hashtable(Map&lt;? extends K,? extends V&gt; t)<\/code><\/pre>\n<h3>Initial capacity, Load Factor<\/h3>\n<p>The Hashtable instance has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of segments in the hashtable, and the initial capacity is simply the capacity at the time the hashtable is created. In the case of the same hash node (called a hash collision), multiple records are stored in a single segment and must be searched sequentially. The load factor indicates how much the hash table can fill up before its capacity is automatically increased.<\/p>\n<p>In general, the default load factor (0.75) offers a good compromise between time and space costs. Higher values reduce the space overhead, but increase the time cost of retrieving a record (which is reflected in most hashtable operations, including get and put). Initial capacity manages the tradeoff between wasted space and the need for repeated operations that are time-consuming.<\/p>\n<p>If the initial capacity is greater than the maximum number of records the hash table will contain divided by its load factor, no rehash operations will ever occur. However, setting the initial capacity too high can waste space. Therefore, when constructing a HashTable, we recommend making the best estimate of how many elements we will store in the collection and choosing the correct initial capacity (and possibly load factor).<\/p>\n<p>If many records are to be created in a hashtable, creating it with a large enough capacity may allow records to be inserted more efficiently than having it perform automatic rehashing as needed to increase the capacity of the table.<\/p>\n<h3>Hash Function<\/h3>\n<p>A well-designed hash function for objects (hashCode) is extremely important because it is what evenly distributes elements into the correct buckets, reducing the likelihood of collisions and maintaining the efficiency and performance of the collection.<\/p>\n<p>When inserting an element into the collection, its hash value is calculated and the segment where the element should be stored is determined. Of course, this is not enough because two objects with the same hashCode may not be the same, so within the same bucket, objects are compared using the <em>equals()<\/em> method to ensure the uniqueness of the inserted elements.<\/p>\n<h2>HashTable &#8211; basic operations<\/h2>\n<p>Some of the basic operations we can perform with HashTable include:<\/p>\n<ul>\n<li><strong>Adding pairs:<\/strong><br \/>\nThe <em>put(key, value)<\/em> method puts a new pair into the table. If a new pair with a matching key is inserted, the old value is overwritten.<\/li>\n<li><strong>Removing Pairs: <\/strong><br \/>\nThe <em>remove(key)<\/em> method removes the pair with the given key.<\/li>\n<li><strong>Emptiness test: <\/strong><br \/>\nThe <em>isEmpty()<\/em> method tells us if the HashTable contains any pair at all.<\/li>\n<\/ul>\n<ul>\n<li><strong>Presence test: <\/strong><br \/>\nThe <em>containsKey(key)<\/em>, <em>containsValue(value)<\/em> methods detect whether a given key or value is present in the table.<\/li>\n<li><strong>Finding the size: <\/strong><br \/>\nThe <em>size()<\/em> method returns the number of pairs in the table.<\/li>\n<li><strong>Clearing the table: <\/strong><br \/>\nThe <em>clear()<\/em> method removes all pairs from the table.<\/li>\n<li><strong>Iteration: <\/strong><br \/>\nUsing the <em>keySet()<\/em>, <em>values()<\/em> or <em>entrySet()<\/em> methods we can iterate over keys, values or integer pairs.<\/li>\n<\/ul>\n<h2>HashTable &#8211; documentation<\/h2>\n<p>For a complete overview of the methods of the HashTable class, see <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/23\/docs\/api\/java.base\/java\/util\/HashTable.html#method-summary\" target=\"_blank\" rel=\"nofollow noopener\">official documentation.<\/a><\/p>\n<h2>HashTable &#8211; advantages and disadvantages<\/h2>\n<h3>Benefits of HashTable<\/h3>\n<ul>\n<li>The<br \/>\nHashTable <strong>synchronization<\/strong> is synchronized, making it safe for use in multi-threaded applications without additional synchronization.<\/li>\n<li><strong>Fast Operations: <\/strong><br \/>\nIdeally, it provides constant-time (O(1)) add, search, and delete operations.<\/li>\n<li><strong>Ease of use: <\/strong> The<br \/>\nAPI is clear and intuitive, making it easy to work with mapping data structures.<\/li>\n<\/ul>\n<h3>Disadvantages of HashTable<\/h3>\n<ul>\n<li><strong>Deprecation: <\/strong><br \/>\nHashTable is considered an older implementation. Modern collections like HashMap offer better performance and more options.<\/li>\n<li><strong>No null values:<\/strong><br \/>\nUnlike some collections, HashTable does not allow null keys or null values, which can be limiting.<\/li>\n<li><strong>Sensitivity to the implementation of hashCode and equals<\/strong><br \/>\nIf the class we store as an element does not have the <em>hashCode()<\/em> and <em>equals()<\/em> methods implemented correctly, this can lead to unexpected behavior and performance degradation.<\/li>\n<li><strong>Performance in case of collisions: <\/strong><br \/>\nWhen there are a large number of collisions (when multiple elements have the same hash code), performance may be degraded because operations may behave more slowly.<\/li>\n<\/ul>\n<h2>HashTable &#8211; when to use it and when not?<\/h2>\n<p>HashTable is suitable in the following cases:<\/p>\n<ul>\n<li>We need a synchronized map without the need for explicit synchronization.<\/li>\n<li>There is no need to store null values.<\/li>\n<\/ul>\n<p>On the other hand, if you don&#8217;t need synchronization or want a similar collection with higher performance, it is recommended to use HashMap.<\/p>\n<h2>Example of using HashTable in Java<\/h2>\n<p><strong>HashTable <\/strong>excels at efficiently storing key-value pairs and retrieving them quickly thanks to a hashing method when we need to retrieve and use them. Therefore, hash tables have versatile uses.<\/p>\n<p>Now we will demonstrate this in a program in which we first create a HashTable using the constructor and store in it the states adjacent to Slovakia. After that, we&#8217;ll show the use of some basic methods for working with the HashTable.<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import java.util.Hashtable;\nimport java.util.Enumeration;\nimport java.util.Set;\n\npublic class Main {\n    public static void main(String[] args) {\n        \/\/ Hashtable creation\n        Hashtable&lt;String, String&gt; skNeighbors = new Hashtable&lt;&gt;();\n\n        \/\/ Adding country codes and country names\n        skNeighbors.put(&quot;SK&quot;, &quot;Slovakia&quot;);\n        skNeighbors.put(&quot;CZ&quot;, &quot;Czech Republic&quot;);\n        skNeighbors.put(&quot;AT&quot;, &quot;Austria&quot;);\n        skNeighbors.put(&quot;HU&quot;, &quot;Hungary&quot;);\n        skNeighbors.put(&quot;UA&quot;, &quot;Ukraine&quot;);\n        skNeighbors.put(&quot;PL&quot;, &quot;Poland&quot;);\n\n        \/\/ Display all country codes and names using Enumeration\n        System.out.println(&quot;Neighboring states of Slovakia:&quot;);\n        Enumeration&lt;String&gt; keys = skNeighbors.keys();\n        while (keys.hasMoreElements()) {\n            String code = keys.nextElement();\n            if(!code.equals(&quot;SK&quot;))\n                System.out.println(code + &quot; - &quot; + skNeighbors.get(code));\n        }\n\n        \/\/ Lookup a country by its code\n        String searchCode = &quot;DE&quot;;\n        if (skNeighbors.containsKey(searchCode)) {\n            System.out.println(&quot;\\n\u2705 Country found for code &quot; + searchCode + &quot;: &quot; + skNeighbors.get(searchCode));\n        } else {\n            System.out.println(&quot;\\n\u274c No country found for code &quot; + searchCode);\n        }\n\n        \/\/ Display the total number of countries in the directory\n        System.out.println(&quot;\\nTotal number of countries in the Hashtable (before remove): &quot; + skNeighbors.size());\n\n        \/\/ Try to remove a country by its code which is not present\n        String removeCode = &quot;DE&quot;;\n        String removedCountry = skNeighbors.remove(removeCode);\n        System.out.println(&quot;Removed country: &quot; + removeCode + &quot; - &quot; + removedCountry);\n\n        \/\/ Try to remove a country by its code\n        removeCode = &quot;SK&quot;;\n        removedCountry = skNeighbors.remove(removeCode);\n        System.out.println(&quot;Removed country: &quot; + removeCode + &quot; -&gt; &quot; + removedCountry);\n\n        \/\/ Check if a specific country exists in the table\n        String searchCountry = &quot;Germany&quot;;\n        if (skNeighbors.containsValue(searchCountry)) {\n            System.out.println(&quot;\u2705 &quot; + searchCountry + &quot; is in the directory.&quot;);\n        } else {\n            System.out.println(&quot;\u274c &quot; + searchCountry + &quot; is NOT in the directory.&quot;);\n        }\n\n        \/\/ Display the total number of countries in the directory\n        System.out.println(&quot;\\nTotal number of countries in the Hashtable (after remove): &quot; + skNeighbors.size());\n\n        \/\/ Clear all country entries\n        skNeighbors.clear();\n        System.out.println(&quot;Country directory cleared. Is it empty? &quot; + skNeighbors.isEmpty());\n\n        \/\/ Display all remaining countries using keySet()\n        System.out.println(&quot;Remaining countries after clearing:&quot;);\n        Set&lt;String&gt; keySet = skNeighbors.keySet();\n        for (String code : keySet) {\n            System.out.println(code + &quot; - &quot; + skNeighbors.get(code));\n        }\n    }\n}<\/code><\/pre>\n<p><strong>The output of this example is:<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-7587\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hastable-vystup-z-prikladu.webp\" alt=\"HashTable - output from this example \" width=\"524\" height=\"448\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hastable-vystup-z-prikladu.webp 524w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hastable-vystup-z-prikladu-300x256.webp 300w\" sizes=\"auto, (max-width: 524px) 100vw, 524px\" \/><\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. Download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashTable.zip\">Java code for <strong>HashTable<\/strong><\/a> here.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The HashTable class is a synchronized data structure for storing key-value pairs. Learn about its advantages, disadvantages and practical uses.  <\/p>\n","protected":false},"author":14,"featured_media":7612,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-7678","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7678","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=7678"}],"version-history":[{"count":1,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7678\/revisions"}],"predecessor-version":[{"id":42900,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7678\/revisions\/42900"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/7612"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=7678"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=7678"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=7678"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}