1

I am stuck in a very simple problem for more then 2 hours. I am trying to create a two dimensional array and fill it with a constructor. However, I couldn't pass this step.

public class Test
{    
     public State [][] test1= new State[4][3];//
     public State test2[][]= new State[4][3];//
     public State [][]test3;
     public State test4[][];

     public class State{
         int position;
         double reward;
         int policy;
     }

     public Test(){
            test1[1][1].position=1; // never worked
            test2[1][3].position=2; //never worked
            test3=new State[4][3];
            test3[1][2].position=3; //never worked
            test4=new State[4][3];
            test4[2][2].position=4;//never worked
     }
}

I am calling above function with following code

Test test= new Test();
Log.e("done","pass"); //I never reach here. the code always stuck on the constructor.
1
  • 1
    Recall that a default value for an object is null. Object[5] array = new Object[5]; allocates an array for 5 object references, but those references are still null. Commented Dec 9, 2014 at 11:05

1 Answer 1

6

When you create the array :

public State [][] test1 = new State[4][3];

you are creating an array that can hold 4 * 3 State instances, but each position in the array is initialized to null.

You need to assign an instance of State to each position in the array before accessing it. If you don't, you'll get a NullPointerException.

For example :

public Test()
{
    test1[1][1] = new State();
    test1[1][1].position = 1;
    ....
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Saved a lot of time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.