要求:按照字符串长度排序
public class TreeSetTest {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new StringComparator());
ts.add("abcd");
ts.add("ab");
ts.add("abcdef");
ts.add("abce");
ts.add("abcdefg");
Iterator it = ts.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
class StringComparator implements Comparator{
public int compare(Object o1,Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0) {
return s1.compareTo(s2);
}
return num;
}
}