Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hash
tree
map
vs

HashMap vs. TreeMap in Java

Educative Answers Team

HashMap and TreeMap both store values in the form of key-value pairs. There are built-in classes, in Java, for both of them.

Similarities

First, let’s take a brief look at the similarities between them:

  1. Manual synchronization​ is required for multi-threaded usage.
  2. Both use an Iterator for traversal.
  3. First incorporated in Java Development Kit 1.2.

Differences

The following are the differences between the two classes:

HashMap

  • Allows one null as a key and multiple nulls as values

  • No iteration order


  • Insertion/deletion requires O(1) time



  • Implements the Map interface

TreeMap

  • Nulls are only allowed as values


  • Iterates in the natural order or the order provided by the Comparator

  • Insertion/deletion requires O(log n) time, where n is the number of elements in the TreeMap

  • Implements NavigableMap interface

Hierarchy

svg viewer
Class diagram showing a part of the hierarchy

RELATED TAGS

hash
tree
map
vs
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring