package cn.itacst.p5.TreeSet.demo;
import java.util.Iterator;
import java.util.TreeSet;
import cn.itacst.p5.comparator.ComparatorByLength;
/*
* 对字符串进行长度排序
*/
public class TreeSetTest {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new ComparatorByLength());
ts.add("aabuc");
ts.add("nab");
ts.add("cba");
ts.add("wbcnuo");
ts.add("hba");
ts.add("gb");
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
package cn.itacst.p5.comparator;
import java.util.Comparator;
public class ComparatorByLength implements Comparator {
@Override
public int compare(Object o1, Object o2) {
String p1 = (String)o1;
String p2 = (String)o2;
int temp = p1.length()-p2.length();
return temp== 0 ? p1.compareTo(p2) : temp;
}
}
|
|