Re: generic sorting?
Hi group,
I want to thank all of you for your help, I tried out what you told me
and think it's really great.
First of all, I have replaced all "int"s with Integer, because Java's
"int"s don't really support genericity. So that's fine now.
Second, I have implemented WeightedObjects like this:
public class WeightedObject<T, C extends Comparable<C>>
implements Comparable<WeightedObject<T, C>>
{
public final T t;
public final C c;
public WeightedObject(T tt, C cc)
{
c = cc;
t = tt;
}
public int compareTo(WeightedObject<T, C> o)
{
return c.compareTo(o.c);
}
} // class
My application code becomes really simple, then:
List<WeightedObject<Plot, Integer>> plots_with_distance
= new Vector<WeightedObject<Plot, Integer>>();
for (Plot plot : plots)
{
plots_with_distance.add(new WeightedObject<Plot, Integer>
(plot,
(int)p.distance_to(plot.point))
);
}
Collections.sort(plots_with_distance);
(I only use the (int) cast to round from a double, so that's no typing
problem. I just don't want to sort by the decimal fraction...)
Third, for learning, I have also changed my original approach to use
Integer and that gives a nice example:
package bob.util;
import java.util.Arrays;
import java.util.Comparator;
public class IndirectComparator<T extends Comparable<T>> implements
Comparator<Integer>
{
protected T[] weight;
public IndirectComparator(T[] w)
{
weight = w;
}
public int compare(Integer i, Integer j)
{
return (weight[i].compareTo(weight[j]));
}
public static <T extends Comparable<T>> void sort(Integer[] index, T[]
weight)
{
Arrays.sort(index, new IndirectComparator<T>(weight));
}
}
It's not as clear as what you suggested, but I like it, too. ;-)
Cheers,
Bob