2

I have constructed a class to mimic a C# struct:

public class Favourite {
    protected  String favName;
    protected  String favText;
    protected String favDelay;
    protected GeoPoint favPoint;
    protected Uri favUri;
}

I want to create an array of this class:

Favourite[] fav;

When I try to access this array:

fav[s].favName = bufr;

I get a NullPointerException. bufr does contain data. I have tracked it down to accessing the array as the following code:

fav[s].favName = "";

also produces a NullPointerException.

I have searched high and low for some indication as to whether or not what I am doing is allowed but cannot find anything.

I suppose my questions are:

Are you allowed to create an array of a class object? If so, how do you refer to that array?

I know I could do this using five separate arrays of the variables but I feel that putting them into a class gives a better structure and is more elegant (I like elegance).

1
  • Have you initialized fav[s] such that favName exists? Commented Jun 28, 2012 at 16:37

3 Answers 3

8

The problem is that fav[s] is null.

I don't know about C#, but in Java, you have to initialize the elements of the array individually; you can't just declare the array and get it automatically filled.

You're going to have to loop through fav and fill it with new Favourite objects.

Either assign fav[s] = new Favourite() the first time you use fav[s], or initialize it all at once by doing

for (int i = 0; i < fav.length; i++) {
  fav[s] = new Favourite();
}
Sign up to request clarification or add additional context in comments.

1 Comment

In C# if the OP had created a struct, it would be a value type, so the array would be full of "empty" values. That would be a bad idea for the given type, mind you - it doesn't feel like a natural value type. I will attempt to convert you to C# tomorrow ;)
3
Favourite[] fav = new Favourite[23]; // Allocate an array of 23 items

Now you have 23 of them!

Comments

1

You need to put items into the array. The declared array simply has null in each slot; you need to do something like fav[s] = new Favourite().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.