0

I am learning java and going over the collections framework currently. I am trying out the API methods for LinkedList and am facing problem with the clone() method. Below is my code

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();
    }
}

When I compile this program, I get the following Error:

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

I tried to lookup but was unsuccessful in finding any reason. What is wrong with the program??

user3504809
  • 3
  • 1
  • 2

2 Answers2

1

List doesnt have a clone method. change that to:

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

if you want to leave it a list, you'll have to do something a little ugly like:

List clonedList = (LinkedList) ((LinkedList) color1List).clone();
yarivt
  • 106
  • 1
  • 4
  • The method `clone()` is available in the `Object` class. So I was struggling with why the compiler is unable to find this method. Thank you so much for your answer we have to typecast it. This makes sense – Vipul Verma Mar 06 '21 at 18:31
-1

The List class does not have a clone method. See here:

How do I clone a generic List in Java?

Consider using ArrayList instead, given all the objects stored are Strings.

Community
  • 1
  • 1
heartyporridge
  • 1,151
  • 8
  • 25