How to Solve Java Error: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Project requirements: convert a comma separated string into a list, and then clone the list and assign it to a new NEWLIST. An error was reported in the title during execution


Original code

public List<String> test() {
    String str = "a,b,c";
    List<String> list = Arrays.asList(str.split(",")); 
    //Only ArrayList and LinkedList have clone method, the purpose of clone is to operate on the list afterwards without changing the value of the original list.
    ArrayList<String> tempList = (ArrayList<String>)list;
    List<String> newList = (List<String>)tempList.clone;
    return newList;


//Just replace the code in the replacement line
ArrayList<String> tempList= new ArrayList<>(list);

Similar Posts: