java linkedlist copy : why my compiler show clone method error?

Viewed 39

This is my code, in this line

 tem_left = (LinkedList) leftover.clone();

my Intellij showed red wave line under .clone() method (BTW, how to discribe this red wave line? hint error?) It says clone() has protected access in Java.lang.Object. This is what I found online that copy a Linkedlist to another one. What did i do wrong and how should I correct it?

package lc_771_Jewels;

import java.util.*;

import java.util.LinkedList;
import java.util.Queue;

public class Jewels_discuss {
    public int count_jewels(String jewels, String stones){
        char[] jewels_kind = jewels.toCharArray();
        char[] stone_list = stones.toCharArray();
        int count = 0;
        Queue<Character> tem_left = new LinkedList<>();
        for (int i = 0; i < stone_list.length; i++) {
           tem_left.offer(stone_list[i]);
        }
        for (int i = 0; i < jewels_kind.length; i++) {
            Queue<Character> leftover = new LinkedList<>();
            char tem_jewel = jewels_kind[i];
            for (int j = 0; j < tem_left.size(); j++) {
                if (tem_jewel!= stone_list[i]  ){
                    leftover.offer(stone_list[i]) ;
                }
                else {
                    count++;
                }
            }
            tem_left = (LinkedList) leftover.clone();
        }
        return count;
    }
}
1 Answers

As the IDEA suggests, which shows clone method of the Queue interface is Object.

protected native Object clone() throws CloneNotSupportedException;

We can not call a protected method from outside.
But, we can choose an implementation that overrides the clone method from protected to public.
We can directly follow the IDEA recommended.
Just change Queue to LinkedList.

// Queue<Character> leftover = new LinkedList<>();
LinkedList<Character> leftover = new LinkedList<>();
Related