- import java.util.Iterator;
- import java.util.TreeSet;
- import java.util.Comparator;
- class ComparatorByLen implements Comparator{
- public int compare(Object o1, Object o2){
- String s1 = (String)o1;
- String s2 = (String)o2;
- int temp = s1.length()-s2.length();
- return temp == 0? s1.compareTo(s2):temp;
- }
- }
- public class TreeSetTest {
- public static void main(String[] args){
- TreeSet ts = new TreeSet(new ComparatorByLen());
- ts.add("Amy");
- ts.add("Tony");
- ts.add("Caroline");
- ts.add("Richa");
- ts.add("Matthew");
- Iterator it =ts.iterator();
- while(it.hasNext())
- System.out.println(it.next());
- }
- }
复制代码 |