Home Java javaTutorial Analysis of the difference between Hashtable and HashMap in java

Analysis of the difference between Hashtable and HashMap in java

May 21, 2017 pm 02:22 PM
hashmap hashtable

Analysis of the difference between Hashtable and HashMap in java, friends in need can refer to it

1. Hashtable is a subclass of Dictionary,

The code is as follows:

 public class Hashtable<K,V>
     extends Dictionary<K,V>
     implements Map<K,V>, Cloneable, java.io.Serializable 
HashMap:
Copy after login

The code is as follows:

public class HashMap<K,V>
    extends AbstractMap<K,V>
     implements Map<K,V>, Cloneable, Serializable
Copy after login

HashMap and Hashtable are both implementation classes of the Map interface;

2. The methods in Hashtable are synchronous (), while the methods in HashMap are by default It's not synchronized. That is to say, in multi-threaded applications, Hashtable can be used safely without special operations; for HashMap, additional synchronization mechanism is required. But the synchronization problem of HashMap can be solved through a static method of Collections:

The code is as follows:

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
Copy after login

This method returns a synchronized Map, which means that the returned Map is a thread safe. It should be noted that when iterating the returned map, you must manually synchronize the returned map, otherwise it will lead to uncertain behavior:

The code is as follows:

Map m = Collections.synchronizedMap(new HashMap());
       ...
   Set s = m.keySet();  // Needn&#39;t be in synchronized block
       ...
   synchronized(m) {  // Synchronizing on m, not s!
       Iterator i = s.iterator(); // Must be in synchronized block
       while (i.hasNext())
           foo(i.next());
   }
Copy after login

3. In HashMap, null can be used as a key, and there is only one such key; there can be one or more keys whose corresponding value is null. When the get() method returns a null value, it can mean that the key does not exist in the HashMap, or it can also mean that the value corresponding to the key is null. Therefore, in HashMap, the get() method cannot be used to determine whether a certain key exists in the HashMap, but the containsKey() method should be used to determine. The key value of Hashtable cannot be null, otherwise: java.lang.NullPointerException.
4.HashTable uses Enumeration, and HashMap uses Iterator.
The above are only superficial differences, and their implementations are also very different.
5. The default size of the hash array in HashTable is 11, and the increasing method is old*2+1. The default size of the hash array in HashMap is 16, and it must be an exponent of 2.
6. The use of hash values ​​is different. HashTable directly uses the hashCode of the object. The code is as follows:

The code is as follows:

int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
Copy after login

And HashMap recalculates the hash value. And use and instead of modulus, such as the put method of HashMap:

The code is as follows:

public V put(K key, V value) {
         if (key == null)
             return putForNullKey(value);
         int hash = hash(key.hashCode());
         int i = indexFor(hash, table.length);
         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
             Object k;
             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                 V oldValue = e.value;
                 e.value = value;
                 e.recordAccess(this);
                 return oldValue;
             }
         }
         modCount++;
         addEntry(hash, key, value, i);
         return null;
     }
Copy after login

The code is as follows:

static int hash(int h) {
         // This function ensures that hashCodes that differ only by
         // constant multiples at each bit position have a bounded
         // number of collisions (approximately 8 at default load factor).
         h ^= (h >>> 20) ^ (h >>> 12);
         return h ^ (h >>> 7) ^ (h >>> 4);
     }
Copy after login

The code is as follows:

static int indexFor(int h, int length) {
         return h & (length-1);
     }
Copy after login

The above is the detailed content of Analysis of the difference between Hashtable and HashMap in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the expansion mechanism of hashmap? What is the expansion mechanism of hashmap? Mar 15, 2023 pm 03:39 PM

The expansion mechanism of hashmap is to recalculate the capacity and replace the original array with a new array. Recalculate all the data of the original array and insert a new array, and then point to the new array; if the array has reached the maximum value before capacity expansion, directly set the threshold to the maximum integer and return it.

How to insert key-value pairs into HashMap using put() method of HashMap class How to insert key-value pairs into HashMap using put() method of HashMap class Jul 26, 2023 pm 11:53 PM

How to insert key-value pairs into a HashMap using the put() method of the HashMap class. HashMap is a very important class in the Java collection framework. It provides a way to store key-value pairs. In actual development, we often need to insert key-value pairs into HashMap, which can be easily achieved by using the put() method of the HashMap class. The signature of HashMap's put() method is as follows: Vput(Kkey,Vvalue)

Based on Java HashMap, how to solve the problem of inserting duplicate Key values Based on Java HashMap, how to solve the problem of inserting duplicate Key values May 09, 2023 am 10:52 AM

Inserting duplicate Key values ​​in javaHashMap To insert duplicate values ​​in HashMap, you first need to figure out how elements are stored in HashMap. Each element stored in the put method Map is a key-value pair, and they are all added through the put method, and the same key will only have one associated value in the Map. The put method is defined as follows in Map. Vput(Kkey,Vvalue); put() method implementation: first hash(key) gets the hashcode() of the key, and hashmap finds the chain where the position to be inserted is based on the obtained hashcode.

Interpretation of Java documentation: Detailed explanation of usage of containsKey() method of HashMap class Interpretation of Java documentation: Detailed explanation of usage of containsKey() method of HashMap class Nov 04, 2023 am 08:12 AM

Interpretation of Java documentation: Detailed explanation of the usage of the containsKey() method of the HashMap class. Specific code examples are required. Introduction: HashMap is a commonly used data structure in Java. It provides efficient storage and search functions. The containsKey() method is used to determine whether the HashMap contains the specified key. This article will explain in detail how to use the containsKey() method of the HashMap class and provide specific code examples. 1. cont

What is the difference between LinkedHashMap and HashMap in java What is the difference between LinkedHashMap and HashMap in java May 02, 2023 am 08:31 AM

1. Explain that Map can basically use HashMap, but HashMap has a problem, that is, the order of iterating HashMap is not the order in which HashMap is placed, or it is out of order. This shortcoming of HashMap often causes trouble, because in some scenarios we expect an ordered Map, which is LinkedHashMap. 2. Difference instances publicstaticvoidmain(String[]args){Mapmap=newLinkedHashMap();map.put("apple","Apple");map.put(&quot

Java adds a Map to another Map using the putAll() function of the HashMap class Java adds a Map to another Map using the putAll() function of the HashMap class Jul 24, 2023 am 09:36 AM

Java uses the putAll() function of the HashMap class to add a Map to another Map. Map is a commonly used data structure in Java and is used to represent a collection of key-value pairs. In Java's collection framework, HashMap is a commonly used implementation class. It provides the putAll() function, which is used to add one Map to another Map to facilitate data merging and copying. This article will introduce how to use the putAll() function and provide corresponding code examples. first,

Java Map performance optimization revealed: Make your data operations faster and more efficient Java Map performance optimization revealed: Make your data operations faster and more efficient Feb 20, 2024 am 08:31 AM

JavaMap is a commonly used data structure in the Java standard library, which stores data in the form of key-value pairs. The performance of Map is crucial to the running efficiency of the application. If the performance of Map is poor, it may cause the application to run slowly or even crash. 1. Choose the appropriate Map implementation Java provides a variety of Map implementations, including HashMap, TreeMap and LinkedHashMap. Each Map implementation has its own advantages and disadvantages. When choosing a Map implementation, you need to choose the appropriate implementation based on the specific needs of the application. HashMap: HashMap is the most commonly used Map implementation. It uses hash tables to store data and has faster insertion, deletion and search speeds.

How to use HashMap to cache data in Java singleton mode How to use HashMap to cache data in Java singleton mode May 13, 2023 am 09:43 AM

1. What is the singleton pattern? The singleton pattern is an object creation pattern that is used to generate a specific instance of an object. It can ensure that only one instance of a class in the system is generated. The singleton implemented in Java is within the scope of a virtual machine. Because the function of loading a class belongs to the virtual machine, a virtual machine will create an instance of the class when it loads the singleton class through its own ClassLoad. In the Java language, such behavior can bring two major benefits: 1. For frequently used objects, the time spent on creating objects can be omitted, which is a very considerable system overhead for those heavyweight objects; 2. Since the number of new operations is reduced, the frequency of system memory usage will also be reduced, which will reduce GC pressure.

See all articles