【问题标题】:convert linklist to arraylist将链接列表转换为数组列表
【发布时间】:2013-12-03 12:36:03
【问题描述】:

我正在尝试创建一种将链表转换为数组列表的方法。

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 应该可以很好地解决这个问题。会有什么问题?

【问题讨论】:

    标签: java arraylist linked-list


    【解决方案1】:

    node.valObject 类型,而 add 需要 Integer。将node.val 类型更改为Integer(或使其成为通用类型),将值转换为Integer 或将ArrayList 更改为ArrayList&lt;Object&gt;

    【讨论】:

      【解决方案2】:

      current.val 的类型为 Object,而 add 方法需要 Integer。要么您需要强制转换,要么您需要使用泛型键入 Node 以确保 node.val 是一个整数。

      【讨论】:

        【解决方案3】:

        我假设“节点”是指链表的头部。与您的问题没有直接关系,但您的迭代是错误的。您首先迭代当前,然后获取它的值。所以你失去了第一个元素的价值。您应该先添加,然后迭代到下一个。

        【讨论】:

          猜你喜欢
          • 2018-01-06
          • 2015-10-11
          • 2019-01-23
          • 1970-01-01
          • 1970-01-01
          • 2012-06-05
          • 1970-01-01
          • 2011-11-26
          相关资源
          最近更新 更多