package collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class Demo1 {
/**
* @练习:按照字符串长度排序
*
* 字符串本身具备计较性,但是他的比较方式不是所需要的,这是要使用比较器
*/
public static void main(String[] args) {
TreeSet ts = new TreeSet(new StringLengthComparator());
ts.add("abcd");
ts.add("cc");
ts.add("cba");
ts.add("aaa");
ts.add("z");
ts.add("hahaha");
Iterator it = ts.iterator();
while(it.hasNext()){
sop(it.next());
}
}
private static void sop(Object o) {
System.out.println(o);
}
}
class StringLengthComparator implements Comparator{
public int compare(Object o1,Object o2){
String s1 = (String) o1;
String s2 = (String) o2;
/*
if(s1.length()>s2.length())
return 1;
if(s1.length()==s2.length())
return 0;
return -1;
*/
//return s1.length()-s2.length();
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0)
return s1.compareTo(s2);
return num;
}
}