当前位置:编程学习 > JAVA >>

请高手帮看看...



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

}
Java linkedlist --------------------编程问答-------------------- 错误信息:The method add(Object) in the type Collection is not applicable for the arguments (int, String)
我把Collection改为List又对了,这是为什么呢? --------------------编程问答-------------------- 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类型就可以了。 --------------------编程问答--------------------
Collection中没那个方法
向下转型成LinkedList才可以
因为你把LinkedList向上转型成Collection
所以只能使用Collection中的方法!
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,