Java Comparator

 

比较函数

Java中,TreeSet和TreeMap都以排序的方式存储元素。具体事由比较函数精确定义排序次序的意义。

定义一个Custom类

Java Comparator
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;
    }
}
Java Comparator

定义CustomComparator类实现Comparator接口

Java 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());
        
    }
    
}
Java Comparator

测试自定义比较函数

Java Comparator
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());
        }
    }
}
Java Comparator

Java Comparator,布布扣,bubuko.com

Java Comparator

上一篇:C++类和对象——学习笔记


下一篇:C++ 术语(C++ Primer)