简体   繁体   中英

Storing ArrayList Data and Converting to a String[][]

I think I have the code correct for storing data in an ArrayList. However, I can't convert the list to a String[][]. Here's my code:

        int row = 0;
        int col = 0;

        String fileInput = JOptionPane.showInputDialog(null, 
                "Please enter the path of the CSV file to read:");

        File file = new File(fileInput);

        BufferedReader bufRdr;
        bufRdr = new BufferedReader(new FileReader(file));
        String line = null;

        // Construct a new empty ArrayList for type String
        ArrayList<String[]> al = new ArrayList<String[]>();

        //read each line of text file
        while((line = bufRdr.readLine()) != null) {
            String[] columnData = line.split(",");
            al.add(columnData);
        }

        // Convert ArrayList to String array
        String[][] numbers = (String[][]) al.toArray(new String[al.size()][16]);

I'm getting an error stating I can't convert to a String[][] type. Any ideas on what I can do?

EDIT: So the conversion problem is solved (the edited code is pasted above) - now its outputting nothing though. I feel like I must have stored the data incorrectly. What should I add/change?

The array will be an Object[] of String[] , so the cast doesn't work. You can (and should) use the toArray() version that supplies the array to populate:

String[][] numbers = (String[][]) al.toArray(new String[al.size()][]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM