- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
- /*
- 练习:按字符串长度排序。
- */
- class Demo{
- public static void main(String [] args){
- TreeSet ts = new TreeSet(new StringLengthComparator());
- ts.add("a");
- ts.add("adf");
- ts.add("aa");
- ts.add("aaa");
- ts.add("aadf");
- ts.add("addf");
- Iterator it = ts.iterator();
- while(it.hasNext()){
- String s = (String) it.next();
- System.out.println(s.length()+"\t"+s);
- }
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
- class StringLengthComparator implements Comparator{
- @Override
- public int compare(Object o1, Object o2) {
- // TODO Auto-generated method stub
- String s1 = (String) o1;
- String s2 = (String) o2;
- int num = s1.length()-s2.length();
- if(num == 0)
- return s1.compareTo(s2);
- return num;
- }
- }
问题:StringLengthComparator 实现了 Comparator接口,可是Comparator接口有 compare 和 equals 两个方法,为何上面的代码只实现了一个方法也能够通过编译,还能正常运行?
|