package com.joe.list;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* 练习:按照字符串长度排序
*
* @author joe
*
*/
public class TreeSetPractice {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new StrLenComparator());
ts.add("abc");
ts.add("abec");
ts.add("at");
ts.add("abcwrw");
Iterator it = ts.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
class StrLenComparator implements Comparator {
//重写compare方法
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
//问题:毕老师说要反过来输出 把s1和s2的位置对调即可,我想知道这样的原理是什么?
//即:int num = new Integer(s2.length()).compareTo(new Integer(s1.length()));
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if (num == 0)
return s1.compareTo(s2); //这里改为:return s2.compareTo(s1)
return num;
}
}