首先是Customer类定义:
然后是CustomerComparator类定义:
实例化对象: TreeSet<Customer> set=new TreeSet<Customer>(new CustomerComparator());
如果改成:
TreeSet<customer> set=new TreeSet<customer>();
在 set.add(c1);语句时报错误:
Exception in thread "main" java.lang.ClassCastException: com.lzw.Customer cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1290)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at com.lzw.CustomerComparator.main(CustomerComparator.java:24)
问题:1、请问为什么会这样?2、TreeSet的集合元素是Customer对象,我也在Customer类实现了compare的方法,为什么在add的时候不是调用这个方法而是在CustomerComparator实现的compare的方法?
treeset这个类,两种方式初始化,有指定比较器 和 没有指定比较器。
查看treeset这个类,父类是treemap,在执行add方法时,其实就是treemap的add。
源码要求,要么传一个comparator比较器给treeset;要么不传比较器时,要求元素类要实现comparable接口。
注:区分
Comparator 比较器的比较方法为 compare
Comparable 的比较方法为compareTo