0

i have a 2 data classes

first:

public class Question {

    public CharSequence question;
    public Answer answers[];

}

second:

public class Answer {

    public CharSequence text;
    public int number;
}

now i want to save an Answer to Question:

Question qstn.answers = new Answer[2];

[...]

But i got an NullPointerException. Whats wrong? Can't I change the length of an Array in an other class?

2
  • I just have to say that this is a good place to use a List or Set instead of an array. A List or Set can grow without having a preset size. Commented May 3, 2011 at 17:28
  • now i use "public ArrayList<Data> answer;" Commented May 6, 2011 at 11:07

6 Answers 6

4

Can't I change the length of an Array in an other class?

That is not the problem.

The problem is that you haven't initialized qstn yet.

What you should be doing is:

Question qstn = new Question();
qstn.answers = new Answer[2];
Sign up to request clarification or add additional context in comments.

Comments

0

Have you created a new instance of Question first e.g.

Question qstn = new Question();
qstn.answers = new Answer[2];

Also unless you're optimising judiciously, then you'd probably want to give encapsulation a go and make the instance variables private. Access through a public API e.g. getters or/and setters.

Also you may want to instantiate answers when the Object is created e.g.

public class Question {

    public CharSequence question;
    public Answer answers[] = new Answer[2];

}

Or you could do this in the constructor of Question (you'd need to add a Constructor, as the compiler will be generating you a non-arg Constructor by default with the way things stand).

Comments

0

You need to instantiate your Question class, first:

Question qstn = new Question();

Comments

0

Try this:

Question qstn = new Question();

qstn.answers = new Answer[2];

Comments

0

Your trying to access the array incorrectly.

 Question qstn = new Question();
 qstn.answers = new Answer[2];

Comments

0

Yes. You can change the length of arrays in another class.

Please check whether you have initialized the variable qstn.

Question qstn = new Question();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.