//package cn.itcast.day01;
import java.util.*;
public class StringTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet ts = new TreeSet(new StringLengthComp());
ts.add("abcd");
ts.add("nids");
ts.add("hahahha");
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//System.out.println("ts = " +ts);
}
}
class StringLengthComp implements Comparator{
public int compare(Object o1,Object o2){
String s1 = (String)o1;
String s2 = (String)o2;
/*
if(s1.length()-s2.length()>0)
return 1;
if(s1.length()-s2.length()==0)
{
return s1.compareTo(s2);
//return 0;
}
return -1;
*/
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
//这里我一开始写成 int num = new Integer(s1).compareTo(new Integer(s2));
//为什么这样不行呢?我查阅API Integer的构造方法是:Integer(String s);
//不就是往里面扔个字符串吗?为什么要加上 .length()呢?
if(num==0)
return s1.compareTo(s2);
return num;
}
}
为什么我用eclipse写的好多行代码下面有黄色的杠杠,并且前面还有感叹号,是不是没有加泛型的原因?
|
|