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

How to use HashMap and TreeMap and what is the difference

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

Share

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

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

Introduction

The key value of TreeMap requires the implementation of java.lang.Comparable, so TreeMap is sorted by default according to the ascending order of key value during iteration; the implementation of TreeMap is based on the red-black tree structure. Suitable for traversing keys (key) in natural or custom order.

The key value of HashMap implements the hash hashCode (), the distribution is hash, uniform, and does not support sorting; the data structure is mainly bucket (array), linked list or red-black tree. Suitable for inserting, deleting, and positioning elements in Map.

Conclusion

If you need to get an ordered result, you should use TreeMap (because the order of the elements in HashMap is not fixed). In addition, because HashMap has better performance, we use HashMap mostly when sorting is not needed.

Development

1. The realization of HashMap and TreeMap

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.

HashMap (): build an empty hash image HashMap (Map m): build a hash image and add all mappings of image m HashMap (int initialCapacity): build an empty hash image HashMap (int initialCapacity, float loadFactor) with specific capacity: build 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.

TreeMap (): build an empty image tree TreeMap (Map m): build an image tree and add all elements in image m TreeMap (Comparator c): build an image tree and sort keywords using a specific comparator TreeMap (SortedMap s): build an image tree, add all mappings in image tree s, and sort using the same comparator as ordered image s

2. HashMap and TreeMap are both non-thread safe

HashMap inherits the AbstractMap abstract class and TreeMap inherits from the SortedMap interface.

AbstractMap abstract class: overrides the equals () and hashCode () methods to ensure that two equal 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: 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.

3. TreeMap is sorted in ascending order by default, how to make it descending

Through a custom comparator

Define a comparator class, implement the Comparator interface, and override the compare method with two parameters, which are compared by calling compareTo, while the compareTo default rule is:

Returns a value of 0 if the parameter string is equal to this string, a value less than 0 if the string is less than the string parameter, or a value greater than 0 if the string is greater than the string parameter.

When you customize the comparator, if you add an extra minus sign when you return, the result of the comparison will be returned in the opposite form, as follows:

Static class MyComparator implements Comparator {

@ Override

Public int compare (Object o1, Object O2) {

/ / TODO Auto-generated method stub

String param1 = (String) o1

String param2 = (String) O2

Return-param1.compareTo (param2)

}

}

After that, initialize a comparator instance through the MyComparator class, passing it as a parameter into the constructor of TreeMap:

MyComparator comparator = new MyComparator ()

Map map = new TreeMap (comparator)

In this way, we can use a custom comparator to implement descending order

Public class MapTest {

Public static void main (String [] args) {

/ / initialize a custom comparator

MyComparator comparator = new MyComparator ()

/ / initialize a map collection

Map map = new TreeMap (comparator)

/ / storing data

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

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

Map.put ("f", "f")

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

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

Map.put ("g", "g")

/ / traverse the output

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

While (iterator.hasNext ()) {

String key = (String) iterator.next ()

System.out.println (map.get (key))

}

}

Static class MyComparator implements Comparator {

@ Override

Public int compare (Object o1, Object O2) {

/ / TODO Auto-generated method stub

String param1 = (String) o1

String param2 = (String) O2

Return-param1.compareTo (param2)

}

}

}

The above is the editor for you to share how to use HashMap and TreeMap and what is the difference, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

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