Re: generic sorting?
danharrisandrews@gmail.com wrote:
willitheowl@gmail.com wrote:
public class IndirectComparator<...> implements Comparator<...> // 1
{
public int compare(int i, int j)
{
return weight[i].compareTo(weight[j]); // 2
}
}
Hi Bob,
Not sure if this is what you had in mind, but see if this helps
(below). Some days I have a heck of a time wrapping my head around
generics and I find Eclipse to have very straight forward tips when I
go astray.
public final class IndirectComparator<T, R extends Comparable<? super
R>>
implements Comparator<T> // 1
{
List<R> weights;
List<T> objs;
public IndirectComparator(List<R> weights, List<T> objs) {
this.weights = weights;
this.objs = objs;
}
public int compare(T i, T j) {
return weights.get(objs.indexOf(i)).compareTo(
weights.get(objs.indexOf(j))); // 2
}
}
If the lists are at all long, using indexOf could cause a performance
problem. It changes the sort complexity from O(n*log(n)) to O(n*n*log(n)).
However, if that is a a problem, it does suggest the alternative of
constructing a HashMap with the objects as keys, and the weights as values:
public final class IndirectComparator<T, R extends Comparable<? super
R>>
implements Comparator<T> // 1
{
Map<T,R> weightMap = new HashMap<T,R>();
public IndirectComparator(List<R> weights, List<T> objs) {
Iterator<R> wIt = weights.iterator();
Iterator<T> oIt = objs.iterator();
while(oIt.hasNext()){
weightMap.put(oIt.next(),wIt.next());
}
}
public int compare(T i, T j) {
return weightMap.get(i).compareTo(weightMap.get(j));
}
}
Patricia