比较函数
Java中,TreeSet和TreeMap都以排序的方式存储元素。具体事由比较函数精确定义排序次序的意义。
定义一个Custom类
public class Custom { private String firstName; private String lastName; /** * Constructor * * @param firstName * @param lastName */ public Custom(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } /** * @override Over write toString() method. */ public String toString() { return firstName+"."+lastName; } }
定义CustomComparator类实现Comparator接口
class CustomComparator implements Comparator<Custom> { @Override public int compare(Custom arg0, Custom arg1) { // TODO Auto-generated method stub return arg0.toString().compareTo(arg1.toString()); } }
测试自定义比较函数
public class TreeMapTestCustomDemo { public static void main(String[] args) { // Create a tree set. TreeMap<Custom, Double> tm = new TreeMap<Custom, Double>(new CustomComparator()); // Add elements to tree set. tm.put(new Custom("John", "Doe"), new Double(22.3)); tm.put(new Custom("Kate", "Gurs"), new Double(20.3)); tm.put(new Custom("Alex", "Wine"), new Double(10.3)); tm.put(new Custom("Itan", "Lisa"), new Double(20.65)); // Get a set of the entries. Set<Entry<Custom, Double>> s = tm.entrySet(); for(Map.Entry<Custom, Double> m:s) { System.out.print(m.getKey()+ ": "); System.out.println(m.getValue()); } } }