请教大神问题!

wy901024 2012-10-01 08:30:15
public class TreeSetTest {

/**
* @param args
*/
public static void main(String[] args) {
TreeSet ts = new TreeSet(new StrLenComparator());
ts.add("a");
ts.add("abc");
ts.add("add");
ts.add("aasss");
ts.add("aadddd");
Iterator it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}

}

class StrLenComparator implements Comparator
{

@Override
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num == 0)
return s1.compareTo(s2);
return num;

}
}



class Student
{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name,int age)
{
this.name = name;
this.age =age;
}
}

问题1:为什么要在泛型后面加上new StrLenComparator();
问题2:为什么每增加一个元素,他总能调用compare方法????如果不写new StrLenComparator();就不能调用,为什么啊?

...全文
108 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wnf2009 2012-10-03
  • 打赏
  • 举报
回复
自己去看源代码里TreeSet 的构造器,
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<E,Object>(comparator));
}

要一个实现Comparator接口的类的实例
wy901024 2012-10-01
  • 打赏
  • 举报
回复
我想知道为什么new一个集合出来的时候,要在那个()中加new StrLenComparator();
NewMoons 2012-10-01
  • 打赏
  • 举报
回复
楼主啊,完全不知道你想干什么。。。
zqfddqr 2012-10-01
  • 打赏
  • 举报
回复
你查查api TreeSet 是有序的 加入的时候要比较 必然用compare了

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧