Le 4 mai 2021, la plateforme Yahoo Questions/Réponses fermera. Elle est désormais accessible en mode lecture seule. Aucune modification ne sera apportée aux autres sites ou services Yahoo, ni à votre compte Yahoo. Vous trouverez plus d’informations sur l'arrêt de Yahoo Questions/Réponses et sur le téléchargement de vos données sur cette page d'aide.
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 réponses
- ?Lv 7il y a 7 ansRéponse favorite
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();
}