Comparison of HashMap and Hashtable is a common question in Java interviews. It is used to test whether programmers can use collection classes correctly and whether they can adapt to different situations and use a variety of ideas to solve problems. The working principle of HashMap, the comparison between ArrayList and Vector, and this question are the most classic questions about the Java collection framework. Hashtable is an obsolete collection class that has existed in the Java API for a long time. It was rewritten in Java 4 and implemented the Map interface, so it has become part of the Java collection framework since then. Hashtable and HashMap are quite easy to be asked in Java interviews, and have even become the most commonly asked questions in collection framework interview questions, so don't forget to prepare for this question before participating in any Java interview.
In this article, we will not only see the difference between HashMap and Hashtable, but also the similarities between them.
The difference between HashMap and Hashtable
HashMap and Hashtable both implement the Map interface, but before deciding which one to use, you must first understand the difference between them. The main differences are: thread safety, synchronization, and speed.
HashMap is almost equivalent to Hashtable, except that HashMap is non-synchronized and can accept null (HashMap can accept null key and value, but Hashtable cannot).
HashMap is non-synchronized, while Hashtable is synchronized, which means that Hashtable is thread-safe and multiple threads can share a Hashtable; without correct synchronization, multiple threads cannot share HashMap. Java 5 provides ConcurrentHashMap, which is a replacement for HashTable and has better scalability than HashTable.
Another difference is that HashMap's iterator (Iterator) is a fail-fast iterator, while Hashtable's enumerator iterator is not fail-fast. So when other threads change the structure of the HashMap (add or remove elements), a ConcurrentModificationException will be thrown, but the remove() method of the iterator itself will not throw a ConcurrentModificationException when removing elements. But this is not a guaranteed behavior, it depends on the JVM. This is also the difference between Enumeration and Iterator.
Because Hashtable is thread-safe and synchronized, it is slower than HashMap in a single-threaded environment. If you don't need synchronization and only need a single thread, then using HashMap will perform better than Hashtable.
HashMap cannot guarantee that the order of elements in the Map will remain unchanged over time.
Some important terms to note:
1) sychronized means that only one thread can change the Hashtable at a time. That is to say, any thread that wants to update the Hashtable must first obtain the synchronization lock, and other threads must wait until the synchronization lock is released before they can obtain the synchronization lock again and update the Hashtable.
2) Fail-safe is related to iterator. If a collection object creates an Iterator or ListIterator, and then other threads try to "structurally" change the collection object, a ConcurrentModificationException will be thrown. However, it is allowed that other threads can change the collection object through the set() method, because this does not "structurally" change the collection. But if the structure has been changed and the set() method is called again, an IllegalArgumentException will be thrown.
3) Structural changes refer to deleting or inserting an element, which will affect the structure of the map.
Can we synchronize HashMap?
HashMap can be synchronized through the following statement:
Map m = Collections.synchronizeMap(hashMap);
Conclusion
There are several major differences between Hashtable and HashMap : Thread safety and speed. Only use Hashtable if you need complete thread safety, and if you are using Java 5 or above, use ConcurrentHashMap.
The above is the detailed content of The difference between HashMap and Hashtable in JAVA. For more information, please follow other related articles on the PHP Chinese website!

hashmap的扩容机制是:重新计算容量,用一个新的数组替换原来的数组。重新计算原数组的所有数据并插入一个新数组,然后指向新数组;如果数组在容量扩展前已达到最大值,则直接将阈值设置为最大整数返回。

如何使用HashMap类的put()方法将键值对插入到HashMap中HashMap是Java集合框架中的一个非常重要的类,它提供了一种存储键值对的方式。在实际开发中,我们经常需要向HashMap中插入键值对,通过使用HashMap类的put()方法可以很轻松地实现这一目标。HashMap的put()方法的签名如下:Vput(Kkey,Vvalue)

1、说明Map基本上可以使用HashMap,但是HashMap有一个问题,那就是迭代HashMap的顺序不是HashMap放置的顺序,就是无序。HashMap的这个缺点往往会带来麻烦,因为有些场景我们期待一个有序的Map,这就是LinkedHashMap。2、区别实例publicstaticvoidmain(String[]args){Mapmap=newLinkedHashMap();map.put("apple","苹果");map.put("

Java文档解读:HashMap类的containsKey()方法用法详解,需要具体代码示例引言:HashMap是Java中常用的一种数据结构,它提供了高效的存储和查找功能。其中的containsKey()方法用于判断HashMap中是否包含指定的键。本文将详细解读HashMap类的containsKey()方法的使用方式,并提供具体的代码示例。一、cont

一、单例模式是什么?单例模式是一种对象创建模式,它用于产生一个对象的具体实例,它可以确保系统中一个类只产生一个实例。Java里面实现的单例是一个虚拟机的范围,因为装载类的功能是虚拟机的,所以一个虚拟机在通过自己的ClassLoad装载实现单例类的时候就会创建一个类的实例。在Java语言中,这样的行为能带来两大好处:1.对于频繁使用的对象,可以省略创建对象所花费的时间,这对于那些重量级对象而言,是非常可观的一笔系统开销;2.由于new操作的次数减少,因而对系统内存的使用频率也会降低,这将减轻GC压

javaHashMap插入重复Key值要在HashMap中插入重复的值,首先需要弄清楚HashMap里面是怎么存放元素的。put方法Map里面存放的每一个元素都是key-value这样的键值对,而且都是通过put方法进行添加的,而且相同的key在Map中只会有一个与之关联的value存在。put方法在Map中的定义如下。Vput(Kkey,Vvalue);put()方法实现:首先hash(key)得到key的hashcode(),hashmap根据获得的hashcode找到要插入的位置所在的链,

Java使用HashMap类的putAll()函数将一个Map添加到另一个Map中Map是Java中常用的数据结构,用来表示键值对的集合。在Java的集合框架中,HashMap是一个常用的实现类。它提供了putAll()函数,用于将一个Map添加到另一个Map中,方便实现数据的合并和拷贝。本文将介绍putAll()函数的使用方法,并提供相应的代码示例。首先,

Java中使用Hashtable类的isEmpty()方法判断哈希表是否为空哈希表是Java集合框架中常用的数据结构之一,它实现了键值对的存储和检索。在Hashtable类中,isEmpty()方法用于判断哈希表是否为空。本文将介绍如何使用Hashtable类的isEmpty()方法,并提供相应的代码示例。首先,我们需要了解一下Hashtable类。Hash


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
