Asking a null for an object’s field throws exception
You established an array with 80 slots that are capable of pointing to Cell
objects. But you never created any Cell
objects. So all eighty slots point to nothing, they are null
.
You then added that array of nulls to an empty ArrayList
. Still no Cell
objects in existence, so the ArrayList
has no Cell
objects, only nulls. You did create a List
of 80 slots, but all slots are empty (null).
You then asked for the object being referenced from the 11th slot of the list (index of 10). There is an eleventh slot. But there is no object reference in the eleventh slot. So you retrieved a null from the list.
From that null you tried to access the value
field defined in Cell
. But you have no Cell
object in hand. You have only a null in hand. A null means nothing. Trying to access a field (or call a method) on a null (on nothing) makes no sense. So Java throws a NullPointerException
.
To verify if you have an object reference in hand rather than a null:
if( Objects.nonNull( eleventhCell ) ) {…}
Define a record using early-access Java 16, an abbreviated way to make your class.
record Cell ( int row, int col, int val ) {} ;
int initialCapacity = 80 ;
List< Cell > cells = new ArrayList<>( initialCapacity ) ;
for( int i = 1 ; i <= initialCapacity ; i ++ )
{
cells.add(
new Cell(
ThreadLocalRandom.current().nextInt( 1 , 100 ) ,
ThreadLocalRandom.current().nextInt( 1 , 100 ) ,
ThreadLocalRandom.current().nextInt( 1_000 , 10_000 )
)
);
}
Cell eleventhCell = cells.get( 10 ) ;
if( Objects.nonNull( eleventhCell ) ) // If in doubt, verify not null.
{
int eleventhVal = eleventhCell.val ;
}
By the way, value
is a poor name for a field in a Java. We use that term as programmers all the time. Discussing “the value of value” will be quite confusing.