簡體   English   中英

LinkedList中的clone()方法

[英]clone() method in LinkedList

我正在學習Java,目前正在研究collections框架。 我正在嘗試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

我嘗試查找,但未找到任何原因。 該程序有什么問題?

列表沒有克隆方法。 更改為:

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

如果要保留列表,則必須做一些難看的事情,例如:

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

List類沒有克隆方法。 看這里:

如何在Java中克隆通用列表?

考慮到所有存儲的對象都是字符串,請考慮使用ArrayList。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM