dimi67
asked on
array of structs in Java
I want to move from C to Java, and I 'm trying to "translate" a piece of code.
For example to make an array of structs in C we have:
struct student{
int code;
char name[50];
float grade;
}students[1000];
How can we make this in Java with classes??
Thnaks in advance
JIM
For example to make an array of structs in C we have:
struct student{
int code;
char name[50];
float grade;
}students[1000];
How can we make this in Java with classes??
Thnaks in advance
JIM
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks! That means that the use of arrey of structs is "useless" in JAVA, since we have Arraylists?
Question: arraylists behave like linked lists with pointers in C?
Question: arraylists behave like linked lists with pointers in C?
Not useless, but used much less than in C. In C, an array is the primary (and without additional libraries the only) choice of container, while in Java you have dynamic containers (ArrayList, LinkedList, HashMap and some rare ones) for ease of use and arrays for speed.
ArrayList behaves like array (indexing is fast, addition may require reallocation and copying), only with dynamic length, for linked list is clas... what is your guess :-)? ... LinkedList.
There are no structs in Java, only classes. Of course class without methods and with public fields is in fact a struct. In C code you than usually have a bunch of functions to work with the struct. When rewriting the code into Java, these should become methods of the "struct", turning it into full-fledged Java class.
ArrayList behaves like array (indexing is fast, addition may require reallocation and copying), only with dynamic length, for linked list is clas... what is your guess :-)? ... LinkedList.
There are no structs in Java, only classes. Of course class without methods and with public fields is in fact a struct. In C code you than usually have a bunch of functions to work with the struct. When rewriting the code into Java, these should become methods of the "struct", turning it into full-fledged Java class.
ASKER
Thanks again!
What is your advice, to learn first C++ or Java, while coming from C?
What is your advice, to learn first C++ or Java, while coming from C?
For a small arrays
//create array of 3 objects
Student[] students = { new Student(), new Student(), new Student() };
For larger arrays
//create array of 1000 objects
Student[] students = new Student[1000];
for (int i = 0; i < students.length; i++) {
students[i] = new Student();
}
For a varying size you could use a List instead of an array
List studentList = new ArrayList();
for (int i = 0; i < 1000; i++) {
studentList.add(new Student());
}