Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between HashMap and TreeMap in Java

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about the difference between HashMap and TreeMap in Java. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Let's first introduce what Map is. In an array, we index its contents by array subscripts, while in Map, we index objects by objects. The object we index is called key, and the corresponding object is called value. This is what we usually call a key-value pair.

HashMap uses hashcode to quickly find its content, while all the elements in TreeMap maintain a fixed order, so if you need to get an orderly result, you should use TreeMap (the order of elements in HashMap is not fixed).

HashMap non-thread safe TreeMap non-thread safe

Thread safety

In Java, thread safety is generally reflected in two aspects:

1. The access of multiple thread to the same java instance (read and modify) will not interfere with each other, which is mainly reflected in the keyword synchronized. Such as ArrayList and Vector,HashMap and Hashtable

The latter is preceded by the synchronized keyword for each method. If you interator a List object and other threads remove an element, the problem arises.

2. Each thread has its own field and is not shared among multiple threads. It is mainly reflected in the java.lang.ThreadLocal class, but there is no Java keyword support, such as static, transient.

1.AbstractMap Abstract Class and SortedMap Interface

AbstractMap abstract class: (HashMap inherits AbstractMap) overrides the equals () and hashCode () methods to ensure that the two equality maps return the same hash code. If two mappings are equal in size, contain the same key, and each key corresponds to the same value in both mappings, the two mappings are equal. The mapped hash code is the sum of the hash codes of the mapping elements, where each element is an implementation of the Map.Entry interface. Therefore, regardless of the internal order of the mapping, two equal maps report the same hash code.

SortedMap interface: (TreeMap inherits from SortedMap) it is used to keep the keys in order. The SortedMap interface provides access to the view (subset) of the image, including two endpoints. Except that sorting is the key that acts on the map, SortedMap is treated the same as SortedSet. The element added to the SortedMap implementation class must implement the Comparable interface, or you must provide an implementation of the Comparator interface to its constructor. The TreeMap class is its only implementation.

two。 Two conventional Map implementations

HashMap: based on hash table implementation. Using the key classes that HashMap requires to add clearly defines hashCode () and equals () [you can override hashCode () and equals ()], and you can tune the initial capacity and load factor to optimize the use of HashMap space.

(1) HashMap (): build an empty hash image

(2) HashMap (Map m): build a hash image and add all mappings of the image m

(3) HashMap (int initialCapacity): build an empty hash image with a specific capacity

(4) HashMap (int initialCapacity, float loadFactor): construct an empty hash image with specific capacity and loading factors.

TreeMap: based on red-black tree. TreeMap has no tuning option because the tree is always in a balanced state.

(1) TreeMap (): build an empty image tree

(2) TreeMap (Map m): build an image tree and add all the elements in the image m

(3) TreeMap (Comparator c): build an image tree and use a specific comparator to sort keywords

(4) TreeMap (SortedMap s): build an image tree, add all mappings in the image tree s, and sort using the same comparator as the ordered image s

3. Two conventional Map performanc

HashMap: suitable for inserting, deleting, and locating elements in Map.

Treemap: suitable for traversing keys in natural or custom order (key).

4. Summary

HashMap is usually a little faster than TreeMap (due to the data structure of trees and hash tables), so it is recommended to use HashMap more often and use TreeMap only when sorted Map is needed.

Import java.util.HashMap

Import java.util.Hashtable

Import java.util.Iterator

Import java.util.Map

Import java.util.TreeMap

Public class HashMaps {

Public static void main (String [] args) {

Map map = new HashMap ()

Map.put ("a", "aaa")

Map.put ("b", "bbb")

Map.put ("c", "ccc")

Map.put ("d", "ddd")

Iterator iterator = map.keySet (). Iterator ()

While (iterator.hasNext ()) {

Object key = iterator.next ()

System.out.println ("map.get (key) is:" + map.get (key))

}

/ / define HashTable for testing

Hashtable tab = new Hashtable ()

Tab.put ("a", "aaa")

Tab.put ("b", "bbb")

Tab.put ("c", "ccc")

Tab.put ("d", "ddd")

Iterator iterator_1 = tab.keySet (). Iterator ()

While (iterator_1.hasNext ()) {

Object key = iterator_1.next ()

System.out.println ("tab.get (key) is:" + tab.get (key))

}

TreeMap tmp = new TreeMap ()

Tmp.put ("a", "aaa")

Tmp.put ("b", "bbb")

Tmp.put ("c", "ccc")

Tmp.put ("d", "cdc")

Iterator iterator_2 = tmp.keySet (). Iterator ()

While (iterator_2.hasNext ()) {

Object key = iterator_2.next ()

System.out.println ("tmp.get (key) is:" + tmp.get (key))

}

}

}

The running results are as follows:

Map.get (key) is: ddd

Map.get (key) is: bbb

Map.get (key) is: ccc

Map.get (key) is: aaa

Tab.get (key) is: bbb

Tab.get (key) is: aaa

Tab.get (key) is: ddd

Tab.get (key) is: ccc

Tmp.get (key) is: aaa

Tmp.get (key) is: bbb

Tmp.get (key) is: ccc

Tmp.get (key) is: cdc Wuhan Renji Integrated traditional Chinese and Western Medicine Hospital

The results of HashMap are not sorted, while the results of TreeMap output are sorted.

Let's get to the topic of this article. Let's give an example of how to use HashMap:

Import java.util.*

Public class Exp1 {

Public static void main (String [] args) {

HashMap h2=new HashMap ()

Random r1=new Random ()

For (int iTuno Bandi)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report