import java.util.*;//此处为什么需要包,没包编译不通过??
class TreeSetTest
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new StrLenComparator());
ts.add("a");
ts.add("ab");
ts.add("abc");
ts.add("bcdf");
ts.add("ab");
Iterator it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class StrLenComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1 = (String)o1;//在此处为什么将o1强转为字符串s1?
String s2 = (String)o2;//同上所述......s2?
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0)
return s1.compareTo(s2);
return num;
}
}
|