请高手帮看看...

JreCC 2013-08-04 10:16:31


package seventh;
import java.util.Collection;
import java.util.LinkedList;
public class LinkedListTest {

public static void main(String[] args) {
Collection c = new LinkedList();
for(int i=0;i<9;i++){
c.add("a"+i);
}
c.add(2,"a10"); //这行提示出错,为什么?
}

}
...全文
127 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
S117 2013-08-05
  • 打赏
  • 举报
回复
Collection中没那个方法 向下转型成LinkedList才可以 因为你把LinkedList向上转型成Collection 所以只能使用Collection中的方法!
2013-08-04
  • 打赏
  • 举报
回复
The method add(Object) in the type Collection is not applicable for the arguments (int, String) 因为你的c是collection类型,但是这个类型不提供c.add(int ,String)这个方法。所以你调用 c.add(2,"a10")就会提示错误。 而List类型中,有一个add方法。 add(int index, E element) 在列表的指定位置插入指定元素(可选操作)。 所以就可以通过。 JAVA会根据你定义的类型来判断该变量具有哪些方法。 如果你想用collection方法通过。你可以进行如下修改 ((LinkedList)c).add(2,"a10"); 将C强制转换为LinkedList类型就可以了。
JreCC 2013-08-04
  • 打赏
  • 举报
回复
错误信息:The method add(Object) in the type Collection is not applicable for the arguments (int, String) 我把Collection改为List又对了,这是为什么呢?

62,621

社区成员

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

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