package com.itheima;
import java.util.*;
class strLengthcompare 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 -1;*/
int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0)
return s1.compareTo(s2);
return num;
}
}
public class Stringex {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet ts=new TreeSet(new strLengthcompare());
ts.add("hsa");
ts.add("hsuajkh");
ts.add("shjkghas");
ts.add("sejkghas");如果此处字符串为“shjkghas”还是没办法插入比较该如何重写Comparator??????
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
} |