-2

I have tried to access an element of my Arrays.asList - List, but I get an NPE.

Main Class:

public class Game  {
    List<Cell> cells = null;


    public Game  () {
        cells = new ArrayList<>();
        cells.addAll(Arrays.asList(new Cell[80])); //Target: Add 80 additional list elements
    }

    public int getSelectedValue () {
        return cells.get(10).value;   //Here I get the NPE, but I need the 10th cell
    }

}

Subclass cell:

public class Cell {
    int row;
    int col;
    int value;
}

How can I instance a List with many objects (100 are required) and have access to those elements with the get() operator?

Artium10
  • 9
  • 1
  • 1
    your array is full of null values – Hovercraft Full Of Eels Jan 04 '21 at 03:05
  • You mean I need to iterate through my full list and instance all of them? Is there a fast way to do so? – Artium10 Jan 04 '21 at 03:07
  • Do: `for (Cell cell : cells) { System.out.println(cell); }` – Hovercraft Full Of Eels Jan 04 '21 at 03:08
  • 1
    Tell me what you see. Note that you should be doing this sort of debugging before coming here – Hovercraft Full Of Eels Jan 04 '21 at 03:09
  • It is not possible to iterate through. I instantly get an NullPointerException: 04:25:49.937 1064-1064/com.example.sudokusolver E/InputEventReceiver: Exception dispatching input event. 04:25:49.937 1064-1064/com.example.sudokusolver E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback 04:25:49.944 1064-1064/com.example.sudokusolver E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference at om.example.sudokusolver.SudokuGame.getSelectedValue(SudokuG – Artium10 Jan 04 '21 at 03:26
  • I can definetly see, that the ArrayList is full of nulls. Is there any other way then to iterate through all cells? – Artium10 Jan 04 '21 at 03:48
  • @Joe There is more to this Question than merely a NullPointerException, as you can see from [my Answer](https://stackoverflow.com/a/65557532/642706). This Question is not a duplicate. – Basil Bourque Jan 04 '21 at 04:45

2 Answers2

1

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

always add a null check on the object before calling a function on it in order to avoid NPE

for eg.

public int getSelectedValue () {
 if(cells !=null && cells.size() >0) 
   { 
    if(cells.get(10) !=null)
       return cells.get(10).value;   
   }
    else return null;
}