3

I have a problem with Collections.sort I cannot solve.

I use a custom comparator to compare integers hashtable-based:

public class HashtableComparator<T> implements Comparator<T> { public HashtableComparator(Map<T,Double> mapScore) { this.mapScore=mapScore; } @Override public int compare(T o1, T o2) { // TODO Auto-generated method stub double d1=mapScore.get(o1); double d2=mapScore.get(o2); if (d1<d2) return -1; else if (d2>d1) return 1; return 0; } public double getScore(T t) { return mapScore.get(t); } private Map<T,Double> mapScore; } 

Now I sort the numbers by:

public static void main(String[] args) { HashMap<Integer,Double> map=new HashMap<Integer,Double>(); ArrayList<Integer> li=new ArrayList<Integer>(); Random rn=new Random(); for (int i=0;i<200;i++) { li.add(i); double r=rn.nextDouble(); map.put(i, r); } ArrayList<Integer> li2=new ArrayList<Integer>(); HashtableComparator<Integer> htComparator= new HashtableComparator<Integer>(map); Collections.sort(li,htComparator); for (Integer i1: li) { System.out.println("i: "+i1+": "+map.get(i1)); } } 

The output looks like this:

... i: 154: 0.9367974470241198

i: 167: 0.9426082679825352

i: 158: 0.9530518486042212

i: 172: 0.9700636428116204

i: 174: 0.9979504046750738

i: 184: 0.011633259785655103

i: 187: 0.03498090300936352

i: 197: 0.07038500463581565

i: 181: 0.07821108293051438

i: 178: 0.12297017501683705

...

completely nonsensen.

Could someone give me a hint what is going wrong there? Thanks

====

Tim

1
  • 2
    Use Double.compare(d1, d2); instead of custom implementation of compare logic Commented Feb 20, 2015 at 9:19

1 Answer 1

3

Instead of writing your own comparison logic, try this:

 @Override public int compare(T o1, T o2) { Double d1 = mapScore.get(o1); Double d2 = mapScore.get(o2); return d1.compareTo(d2); } 

because the Double wrapper class implements the Comparable interface.

Sign up to request clarification or add additional context in comments.

1 Comment

a thanks, now it works. i just saw there was also an error in my comparator, the else case should be: else if d2<d1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.