Reputation: 51
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).
Upvotes: 2
Views: 16395
Reputation: 95588
Favourite[] fav = new Favourite[23]; // Allocate an array of 23 items
Now you have 23 of them!
Upvotes: 3
Reputation: 40346
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()
.
Upvotes: 1
Reputation: 198163
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();
}
Upvotes: 8