Search code examples
javacomparatortreemap

Change comparator of treemap during runtime


I see that the only way to set a comparator is via the TreeMap constructor. For instance:

 TreeMap myMap = new TreeMap(myComparator);

However, I would like to decide what type of comparator to use during runtime. I could create multiple TreeMaps or a new instance of one, but I find that it leaves a bigger memory footprint.

Is there a way to achieve this? Or is there a design flaw on my end?


Solution

  • I suggest that you defer the creation of the TreeMap until you know which Comparator will be appropriate. If this is not possible (e.g. because you need to initialize other objects with a reference to the TreeMap), consider hiding the TreeMap behind a method or class that will lazily initialize it, or using the Factory pattern.

    If this is also impossible, initialize the TreeMap with your own Comparator implementation, and make the decision there (compareTo() won't be invoked until you start adding items to the TreeMap). If you go this route, you must take great care to not change the comparator behavior after you've started adding items to the tree!

    As for why TreeMap (or most other collections that take a Comparator) won't allow you to change the Comparator, see @Evgeniy Dorofeev's answer.