Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a Treemap resort if a TreeMap passed to it as Map

We define a new TreeMap in a method and pass it to another method:

TreeMap aTreeMap = new TreeMap();
//call another method to doSomething with map
doSomeThing(aTreeMap)

The doSomething() is as below:

 doSomething(Map aMap){  
    //Make a new copy of
    TreeMap aTreeMap = new TreeMap(aMap);    
}

Will the new TreeMap resort the data?!

like image 830
Alireza Fattahi Avatar asked Mar 14 '23 02:03

Alireza Fattahi


1 Answers

Looking at the implementation of TreeMap on grepcode.com, it has these constructors (among others):

public TreeMap(Map<? extends K, ? extends V> m) {
    comparator = null;
    putAll(m);
}

public TreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }
}

So it makes a difference when you create a new TreeMap from a Map or a SortedMap (such as another TreeMap). In case of the latter, it will not re-sort.

like image 182
janos Avatar answered Mar 23 '23 21:03

janos