Add wechat: code_7Steps, note “enter the group”, invite you to join the technical exchange group crowded with big talent!

In the process of programming development, key-value pair access is often involved, and the representative ones in Java are HashMap and TreemMap.

The implementation of these two Map interfaces is widely used to store key-value pairs and support daily operations on the data set, such as adding, deleting, modifying, and searching.

In this article, I’ll detail the core similarities and differences between TreeMap and HashMap through examples.

In Java, all Map implementations store key-value pairs, but the implementation-based differences are minimal. Compared to TreeMap, HashMap is widely used in the daily development of the collection framework. Both use the internal bucket concept, but it is converted to a TreeNode structure as any bucket partition becomes larger.

HashMapandTreeMapThe similarities between

Before you understand the differences between the two classes, take a look at what they have in common.

These two classes have the following in common:

  • HashMapandTreeMapClass implementsMap<K, V>.Cloneable.SerializableInterface, and extendAbstractMap<K, V>class
  • Both store values based on keys
  • The key value is guaranteed to always be unique, and if we add the same key again, the old value will be replaced by the new value
  • Neither is thread-safe, since a runtime exception is thrown if the original Map is modified during iteration

HashMapThe sample

In the following example, I mainly implement the following functions:

  • We use theput()Methods toHashMapSeveral values have been added
  • The outputHashMapAll the values
  • Print values using iterators
  • From the originalHashMapDelete key “0333” from
  • fromHashMapAn exception occurs when a key is deleted from

Sample code:

import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; publicclass HashMapExamples { public static void main(String[] args) { Map<String, String> hashMap = new HashMap<>(); hashMap.put("0111", "one's"); hashMap.put("0222", "two's"); hashMap.put("0333", "three's"); hashMap.put("0444", "four's"); hashMap.put("0111", "one's modified"); System.out.println("HashMap values are - " + hashMap); System.out.println("Iterating Hashmap and modifying the values"); Set<String> keys = hashMap.keySet(); Iterator<String> iterator = keys.iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key - " + key + ", value - " + hashMap.get(key)); if (key == "0333") { hashMap.remove(key); }}}}Copy the code

Output:

HashMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating Hashmap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490)
    at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513)
    at com.javaprogramto.collections.hashmap.HashMapExamples.main(HashMapExamples.java:29)
Copy the code

TreeMapThe sample

Following a similar example for TreeMap, we use the put() method to add some values to TreeMap in the following example. Next, print all the values of TreeMap in sorted order. A further attempt was made to print values using iterators, and the key “0333” was removed from TreeMap. Removing keys from TreeMap causes a runtime exception.

Sample code:

package com.javaprogramto.collections.treemap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; publicclass TreeMapExamples { public static void main(String[] args) { Map<String, String> treeMap = new TreeMap<>(); treeMap.put("0111", "one's"); treeMap.put("0222", "two's"); treeMap.put("0333", "three's"); treeMap.put("0444", "four's"); treeMap.put("0111", "one's modified"); System.out.println("treeMap values are - " + treeMap); System.out.println("Iterating treeMap and modifying the values"); Set<String> keys = treeMap.keySet(); Iterator<String> iterator = keys.iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key - " + key + ", value - " + treeMap.get(key)); if (key == "0333") { treeMap.remove(key); }}}}Copy the code

Output:

treeMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating treeMap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)
    at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1262)
    at com.javaprogramto.collections.treemap.TreeMapExamples.main(TreeMapExamples.java:29)
Copy the code

HashMapandTreeMapThe difference between

Here are the main differences between the two classes:

  1. TreeMapImplement the NavigableMap interface instead of the Map interface
  2. HashMapIt’s based on hash tables,TreeMapIs implemented based on tree structures such as red-black trees
  3. HashMapOnly one empty key and multiple null values are allowed,TreeMapNo empty keys are allowed, but null values are allowed
  4. HashMapInstead of sorting the keys,TreeMapIt sort the keys
  5. HashMapthanTreeMapFast, because hashMap doesn’t sort, so it can be usedput()andget()Method for easy access to insert and retrieve with constant O(1) time complexity
  6. HashMapuseequals()Method to repeat key comparisons, but forTreeMapThe key is based oncompareTo()Method to compare and sort

conclusion

In this paper, the similarities and differences between HashMap and TreeMap classes are introduced through simple examples. There are still many contents worth knowing and learning about the two people. If you are interested, you can refer to relevant information by yourself.


Dry recommended

In order to facilitate everyone, I spent half a month’s time to get over the years to collect all kinds of iso technical finishing together, content including but not limited to, Python, machine learning, deep learning, computer vision, recommendation system, Linux, engineering, Java, content of up to 5 t +, all dry goods send to you, hope to be able to support a thumb up!

Pan.baidu.com/s/1eks7CUyj…