casting Arrays.asList causing exception: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

I had the following exception with the following code


package util;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;

import play.Logger;
import au.com.bytecode.opencsv.CSVReader;

public class CSVReaderUtil {

    public static ArrayList> readCSVFile (String fileName) {
        
        CSVReader csvReader = null;
        ArrayList> csvDataList = new ArrayList<>();
        
        try {
            
            csvReader =  new CSVReader(new FileReader(fileName));
            String[] row;
            
            while ((row = csvReader.readNext()) != null) {
                
                csvDataList.add((ArrayList)Arrays.asList(row)); 
            }
        }
        catch (Exception e) {
            Logger.error("Error: ", e);
        } finally {
            if(null != csvReader) {
                try {
                    csvReader.close();
                } catch (Exception e) {
                }
            }
        }
        
        return csvDataList;
    }
}


For me (using Java 1.7), the first snippet gives the same exception as the second one. The reason is that the Arrays.asList(..) method does only return a List, not necessarily an ArrayList. Because you don't really know what kind (or implementation of) of List that method returns, your cast to ArrayList is not safe. The result is that it may or may not work as expected. From a coding style perspective, a good fix for this would be to change your stuff declaration to: List> stuff = new ArrayList>(); which will allow to add whatever comes out of the Arrays.asList(..) method.

No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days