[Biojava-dev] SortedMap comparator question

Thomas Down td2@sanger.ac.uk
Wed, 9 Oct 2002 22:53:20 +0100


I don't think there's anything specifically illegal about doing
this (although do, of course, check the javadocs).  I do, however,
have a couple of concerns about how this will work out in practice.
IIRC, TreeMap really is a tree-based data structure, which is
accessed by comparing a new object to objects already in the tree
(using the specified comparator).  If you look up an unknown key,
the comparator you list below will fail (NullPointerException).
Obviously, this is fixable (just make unknown keys sort above or 
below all defined keys).  However, more seriously, I think the
same situation might also apply during inserts.  In this case,
the obvious workaround doesn't help, since it means that they new
entry will probably be inserted into the wrong part of the tree.

There's another, lesser, issue, if you try inserting two different
keys which map to the same value.

How about defining a little datablob class which is an 
Object-double pair. defining a comparator over those, then
just using a SortedSet?

     Thomas.


On Wed, Oct 09, 2002 at 05:22:59PM -0400, Michael L. Heuer wrote:
> 
> Sorry for this offtopic question, but does anyone know if it is legal to
> use a comparator that compares values stored in the map to sort keys in a
> SortedMap?
> 
> Hmm .. I guess that might be hard to read.
> 
> Something like
> 
> class MySortedMap extends TreeMap implements SortedMap
> {
>   public MySortedMap()
>   {
>     super(new DoubleValueComparator());
>   }
> 
>   private static class DoubleValueComparator
>     implements Comparator
>   {
>     public int compare(Object o1, Object o2)
>     {
>       if (o1.equals(o2))
>         return 0;
> 
>       double d1 = ((Double) MySortedMap.this.get(o1)).doubleValue();
>       double d2 = ((Double) MySortedMap.this.get(o2)).doubleValue();
> 
>       return (int) (d1 - d2);
>     }
>   }
> }
> 
> for a map of Objects -> Doubles.