【Java】【52】處理報錯:java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList


前言:項目需求:將一個逗號分隔的字符串轉換成list,然后將該list克隆后賦值給一個新的newList。執行時出現了標題中的報錯

正文:

原代碼

public List<String> test() {
    String str = "a,b,c";
    List<String> list = Arrays.asList(str.split(",")); 
    //只有ArrayList和LinkedList有clone方法,clone的目的是為了之后對list的操作可以不改變原list的值
    ArrayList<String> tempList = (ArrayList<String>)list;
    List<String> newList = (List<String>)tempList.clone;
    return newList;
}

改正

//替換其中裝換的那句代碼就可以了
ArrayList<String> tempList= new ArrayList<>(list);

 

參考博客:

https://blog.csdn.net/keq_keq/article/details/89762671


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM