Skip to content
Advertisement

Can’t use array of objects

I have a Main and a Cars classes, and I am trying to create an array of Cars and have it like this:

JavaScript

then I have this for:

JavaScript

to try and fill it but I get this error:

JavaScript

Can you help me pointing what I’m doing wrong please?

Advertisement

Answer

You create Cars array, as:

JavaScript

but you never put any car instance into that array.

Afterwards, with:

JavaScript

you are trying to fetch the ith element from the list array and access its field, but you have nulls in your array (which is the default value array of reference type is initialized with), therefore, fields brand and price will not be resolved as you’re accessing them on the null reference.

Instead, you should first create an object(s) and put that(those) into your array.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement