Search code examples
javaarraysarraylistprimitive

Why do I need to convert from Integer[] to int[]?


I have the following code

public static int[] readCSV() {
    ArrayList<Integer> entries = new ArrayList<>();
    try {
        File file = new File("someDataFile.csv");
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line = "";
        String[] row;
        while((line = br.readLine()) != null) {
            row = line.split(",");
            for(String value : row) {
                int entry = Integer.parseInt(value);
                entries.add(entry);
            }
        }
        br.close();
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }
    int[] IDs = entries.toArray();
    return IDs;
}

Every entry of the csv is an integer stored as a string. I get the following error: "Type mismatch: cannot convert from Object[] to int[]". As far as I understand, "entries" is not an Object[] here, it's an ArrayList<Integer>.

I was using an example given on geeksforgeeks. That didn't work and I'm not sure why.

I also checked the previous answers to the same question, and the top answer works for me. That said, I still don't have an int[], I only have Integer[]. Then I have to do this to convert from Integer[] to int[]. My question is why do I have to do all that instead of int[] IDs = entries.toArray();?

If I do

int[] IDs = new int[entries.size()];
for (int i=0; i<entries.size(); i++) {
    IDs[i] = entries.get(i);
}

it works fine. Why is that different from int[] IDs = entries.toArray()?

Is there a better way to get the contents of the csv file in an int[]?


Solution

  • First, to answer your question, because a collection (like ArrayList) can only contain object instances. That means you must use the Integer wrapper type instead of the int primitive type. However, in Java 8+, there are simple ways to perform that conversion. I would also strongly recommend a try-with-Resources over manually closing the BufferedReader. I also simplified the code a little. Like,

    public static int[] readCSV() {
        List<Integer> entries = new ArrayList<>();
        File file = new File("someDataFile.csv");
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] row = line.split("\\s*,\\s*"); // Consume white space
                for (String value : row) {
                    entries.add(Integer.parseInt(value));
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return entries.stream().mapToInt(Integer::intValue).toArray();
    }