Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
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?
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.
3 Answers
- Empire539Lv 77 years agoFavorite 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();
}