Collection List接口的问题

vincentjang 2008-11-07 09:31:48

import java.util.*;

public class Te {
public static void main(String[] args){
List d = new LinkedList();//如果把List改成Collection的话 Collections.sort(d);这里出错,为什么
d.add(new Name("jim","green"));
d.add(new Name("as","das"));
d.add(new Name("edward","silly"));
d.add(new Name("Luis","figgo"));
Collections.sort(d);
System.out.println(d);
}
}

class Name implements Comparable{
private String firstName,lastName;
public Name(String firstName,String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName(){ return firstName; }
public String getLastName(){ return lastName; }
public String toString(){ return firstName + " " + lastName; }

public int compareTo(Object o) {
Name n = (Name)o;
int c = lastName.compareTo(n.lastName);
return ( c!=0 ? c : firstName.compareTo(n.firstName));
}
}


就是上面的搞不太明白。。
...全文
81 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
vincentjang 2008-11-08
  • 打赏
  • 举报
回复
好好看API去了,谢谢各位
FL1429 2008-11-07
  • 打赏
  • 举报
回复
o
ssqtjffcu 2008-11-07
  • 打赏
  • 举报
回复

只有Collections.sort(List<T> list)
没有Collections.sort(Collection<T> collection)
所以不能..
lovegenii 2008-11-07
  • 打赏
  • 举报
回复
小哥啊!!!!你一定是没有认真的看aPI
sort(List<T> list) : Sorts the specified list into ascending order, according to the natural ordering of its elements.
这里不是说了吗?人家只接受list.你确把list改成Collection
vincentjang 2008-11-07
  • 打赏
  • 举报
回复
JDK 不提供此接口的任何直接实现:它提供更具体的子接口(如 Set 和 List)实现。

是不是这个?
justinavril 2008-11-07
  • 打赏
  • 举报
回复
因为Collections.sort()的方法不支持这个类型的参数
fosjos 2008-11-07
  • 打赏
  • 举报
回复
多看api帮助手册,或者直接看源代码,很明显,函数定义的参数是List

62,614

社区成员

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

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