String str[] = new String[5];
CSVReader read = new CSVReader(new FileReader("abc.csv"));
str = read.readNext();
str[3] = "A";
In the above code snippet, I am declaring array of strings of size 5. I am using OpenCSV to parse my CSV file. The CSV file has three columns. The statement str = read.readNext() stores values in str[0], str[1], str[2]. The problem is that after this statement is executed, the size of the array str is reduced to 3. Due to this str[3] throws ArrayIndexOutOfBounds exception. Why the size is reduced to 3 from 5 ?
The size of an array
can NOT be changed, but read.readNext
is returning a brand new array with probably a different size in which you assigning it to the same variable str
.
readNext
is returing a whole new array for you:
String str[] = new String[5];
Means "Make 'str' refer to a new String array of length 5"
CSVReader read = new CSVReader(new FileReader("abc.csv"));
Make a new CSVReader called 'read'
str = read.readNext();
call 'readNext' and set 'str' to refer to the result (even though I just asked you to use that name to refer to a new, empty, String array of length 5)
str[3] = "A";
Now access the 4th element from the readNext result.
Incidentally, because you didn't create the array that 'str' refers to, you don't know its size, so using .length
on it is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With