Task 1 of 5 · 0 solved · 5 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.3 Ordered collections — TreeMap keeps keys sorted

Lesson

Когда порядок всё-таки нужен

Everything in this module so far came with a warning: a HashMap gives no guarantee about the order of its keys. TreeMap removes that warning — it keeps the keys sorted, always.

You change one word:

Map<String, Integer> m = new TreeMap<String, Integer>();

Everything else — put, get, containsKey, entrySet — works exactly the same, because both are Map.


Что это даёт

m.put("pear", 3);
m.put("apple", 5);
m.put("fig", 1);
System.out.println(m);   // {apple=5, fig=1, pear=3}  — always this order

Now printing the map is safe, iteration is predictable, and there are extras: firstKey() and lastKey().

The price: TreeMap keeps order by comparing keys, so it is slightly slower than HashMap and requires keys that can be compared — which is why Comparable from module 8 matters here.


▶ Try it: run this, then change something and run it again.



A TreeMap keeps its keys...


Switching from HashMap to TreeMap requires...


Type exactly what this program prints.

import java.util.Map;
import java.util.TreeMap;

public class Main { public static void main(String[] a){
    TreeMap<String, Integer> m = new TreeMap<String, Integer>();
    m.put("dog", 1);
    m.put("ant", 2);
    m.put("cat", 3);
    System.out.println(m);
    System.out.println(m.firstKey());
}}

What does TreeMap cost compared to HashMap?


True or false?