-1

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[]?

  • 1
    *My question is why do I have to do all that instead of int[] IDs = entries.toArray();?* : Simple answer: Integer and int are not same. See [this](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html) - in particular the statement : "The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. " – SomeDude Jun 18 '22 at 18:00

2 Answers2

1

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();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thanks for that. Is the stream solution better than the for loop solution? Does it do it faster or with less memory? – DimitrisMel Jun 18 '22 at 17:56
  • @DimitrisMel That number (`3692851740`) is outside the range of an `int`. Sounds like you want to `long`(s). It uses less code. Less code is better than more code. Faster or less memory are not the only metrics. Good luck! – Elliott Frisch Jun 18 '22 at 18:05
0

List#toArray always returns an Object[]. The closest you can get is entries.toArray(new Integer[0]) to get an Integer[].

To get an int[] you can use the Streams API or loop over the List and copy it over to an array.

Integer[] arr = list.toArray(new Integer[0]);
int[] arr2 = list.stream().mapToInt(i -> i).toArray();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80