我正在尝试创建一个将链表转换为arraylist的方法。
public ArrayList<Integer> toList(){
//Node node;
Node current = node;
while(current != null){
current = current.next;
array.add(current.val);
}
}
并显示错误
no suitable method found for add(Object)
method ArrayList.add(int,Integer) is not applicable
(actual and formal argument lists differ in length)
method ArrayList.add(Integer) is not applicable
(actual argument Object cannot be converted to Integer by method invocation conversion)
我目前正在使用JDK 1.7,从我在本论坛中发现的内容来看,JDK 1.7应该对这个问题很好。会出现什么问题?
答案 0 :(得分:4)
node.val
的类型为Object
,而add则需要Integer
。将node.val
类型更改为Integer
(或将其设为通用),将值转换为Integer
或将ArrayList
更改为ArrayList<Object>
答案 1 :(得分:3)
current.val
的输入为Object
,而add方法则需要Integer
。您需要演员表,或者需要使用泛型键入Node
以确保node.val
是整数。
答案 2 :(得分:1)
我假设“节点”指的是链表的头部。与您的问题没有直接关系,但您的迭代是错误的。您首先迭代当前,然后您正在获取它的值。所以你失去了第一个元素的价值。你应该先添加,然后迭代到下一个。