Java: How to use an array of structures (sorry, classes)?

Im not an expert when it comes to Java, but have been writing C/C++ code for many years. So what I need to do in java is create an array of structures and be able to use it in my code.

OK, in C/C++ I would do it this way (and I will simplify it):

typedef struct mystruct{
char name[20];
int age;
};
....
in main:
mystruct People[20]; //this creates an array of 20 structs.

People[0].age = 40;
strcpy(People[0].name, "justme");
etc...

How can I do this sort of thing in Java? Some sample code for doing the above example would be nice.


This is what I tried in Java:

class myclass{
String Name;
int age;
};
...

myclass People[] = new myclass[20];

But if I try:
People[0].Name = "justme";

I get a null pointer exception. What am I doing wrong?

2014-04-18T13:46:19Z

EDIT: Just thought I would mention that the actual structure I will be using is bigger (7 strings) and the array of these structures needs to be at least 256.

?2014-04-18T14:10:01Z

Favorite Answer

You've almost got it. When you do:

myclass People[] = new myclass[20];

You're creating an array called People, where each element is of type "myclass". (Though, I'll mention it here that this is generally the reverse of typical Java syntax. In Java, class names should have a capital letter, while variable names should be lowercase; so MyClass people[] = new MyClass[20] is preferable.)

However, just because you created the array itself, it doesn't mean you created the elements inside it. You have to instantiate each element of the array in order to use it. So:

MyClass people[] = new MyClass[20];

people[0] = new MyClass();
people[0].name = "Empire539";

You can also use a for loop or something to instantiate all the objects at once, if you'd like:
for (int i = 0; i < people.length; i++) {
    people[i] = new MyClass();
}

?2016-12-12T17:01:47Z

Array Of Structures

francene2016-09-28T11:30:55Z

Array Of Structs