Re: ordering of items in a treemap
Andrea Francia wrote:
angelochen960@gmail.com wrote:
Hi,
I have code:
TreeMap<String, String> shoeSize = new TreeMap<String, String>();
shoeSize.put("8", "8");
shoeSize.put("8.5", "8.5");
shoeSize.put("10", "10");
System.out.println(shoeSize.toString());
I got:
{10=10, 8=8, 8.5=8.5}
I'd like to get the order same inserted:
{8=8, 8.5=8.5, 10=10}
any idea? thanks
From TreeMap docs:
> The map is sorted according to the natural ordering of its keys, or
by a Comparator provided at map creation time, depending on which
constructor is used.
Create a subclass that log the order of the inserted keys and create a
Comparator that uses these information.
That'd be an implementing class of java.util.Comparator. It's a subtype, but
not a subclass. What class were you suggesting to extend?
There's no need for the additional complexity and overhead of logging
anything. Just write a Comparator and pass it to the TreeMap constructor.
You can't use a List instead?
Good suggestion - note that the Map as shown does not associate keys to
values, but values to themselves. OTOH, the List won't sort it for you, so
you still need to write a Comparator.
--
Lew