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"); //这行提示出错,为什么?
}}
Javalinkedlist

解决方案 »

  1.   

    错误信息:The method add(Object) in the type Collection is not applicable for the arguments (int, String)
    我把Collection改为List又对了,这是为什么呢?
      

  2.   

    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类型就可以了。
      

  3.   


    Collection中没那个方法
    向下转型成LinkedList才可以
    因为你把LinkedList向上转型成Collection
    所以只能使用Collection中的方法!