【问题标题】:clone() method in LinkedListLinkedList 中的 clone() 方法
【发布时间】:2014-05-19 01:26:07
【问题描述】:

我正在学习 Java,目前正在研究集合框架。我正在尝试 LinkedList 的 API 方法,并且面临 clone() 方法的问题。下面是我的代码

import java.util.List; 
import java.util.ArrayList;
import java.util.Collection;
import java.util.ListIterator;
import java.util.LinkedList;

public class LinkedListTest
{
    public static void main(String[] args)
    {
        String[] colors1 = {"Red", "Blue"};

        List<String> color1List = new LinkedList<String>();

        for(String color:colors1)
            color1List.add(color);

        List clonedList = (LinkedList) color1List.clone();
    }
}

当我编译这个程序时,我得到以下错误:

LinkedListTest.java:51: cannot find symbol
symbol  : method clone()
location: interface java.util.List<java.lang.String>
                List<String> clonedList = (LinkedList<String>)color1List.clone();
                                                                    ^
1 error

我试图查找,但没有找到任何原因。程序有什么问题??

【问题讨论】:

    标签: java linked-list


    【解决方案1】:

    List 没有克隆方法。 将其更改为:

    LinkedList<String> color1List = new LinkedList<String>();
    

    如果你想给它留下一个列表,你必须做一些丑陋的事情,比如:

    List clonedList = (LinkedList) ((LinkedList) color1List).clone();
    

    【讨论】:

    • clone() 方法在 Object 类中可用。所以我一直在为为什么编译器找不到这个方法而苦苦挣扎。非常感谢您的回答,我们必须对其进行类型转换。这是有道理的
    【解决方案2】:

    List 类没有克隆方法。见这里:

    How do I clone a generic List in Java?

    考虑使用 ArrayList,因为所有存储的对象都是字符串。

    【讨论】:

      猜你喜欢
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2018-08-16
      • 2018-06-10
      相关资源
      最近更新 更多