日期:2014-05-20  浏览次数:20996 次

关于java中Comparator排序:重写了compare()方法,但不管用
在MyCom类中重写了compare方法,但输出结果仍然是按照名字(first name)排序,而不是按照姓(last name)排序。代码如下:

package com.util;
import java.util.*;
/*
 * use a comparator to sort accounts by last name
 */
public class ComparatorDemo2 {
public static void main(){
//create a tree map
TreeMap<String, Double> tm = new TreeMap<String, Double>(new MyCom()); 

tm.put("John Doe", new Double(34434.23));
tm.put("Tom Smith", new Double(50000));
tm.put("Jane Baker", new Double(12343.323));
tm.put("Tod Hall", new Double(-100000));
tm.put("Ralph Smith", new Double(250));
tm.put("Tood Hell", new Double(340));
tm.put("Jimmy Linnister", new Double(980));
tm.put("Wood Hell", new Double(2333));
tm.put("John Hell", new Double(2343));

Set<Map.Entry<String, Double>> set= tm.entrySet();

for(Map.Entry<String, Double> e: set){
System.out.println(e.getKey()+": ");
System.out.println(e.getValue());
}
System.out.println();
double balance = tm.get("Ralph Smith");
tm.put("Ralph Smith", balance+1000000);
System.out.println("Ralph Smith的账户余额:"+tm.get("Ralph Smith"));
}
}
class MyCom implements Comparator<String>{

@Override
public int compare(String a, String b) {
// TODO Auto-generated method stub
int i, j, k;
String as=a, bs=b;
i = as.lastIndexOf(' ');
j = bs.lastIndexOf(' ');
k = as.substring(i).compareTo(bs.substring(j));
if(k==0)return as.compareTo(bs); //last name match, check the entire name
else return k;
}

}



------解决方案--------------------
你的结果没有问题,是按lastName 进行排序,是你理解的问题??
Java code

//////////////////result/////////
Jane Baker: 
12343.323
John Doe: 
34434.23
Tod Hall: 
-100000.0
John Hell: 
2343.0
Tood Hell: 
340.0
Wood Hell: 
2333.0
Jimmy Linnister: 
980.0
Ralph Smith: 
250.0
Tom Smith: 
50000.0

Ralph Smith的账户余额:1000250.0

------解决方案--------------------
假如英文全名叫Jane Baker:
1、你想比较Jane这部分呢,MyCom类中就如此改
k = as.substring(0,i).compareTo(bs.substring(0,j));

2、假如你想比较Baker这部分呢,就啥都不需要改。