tags:

views:

93

answers:

3

Hi, everyone,

I want to ask a question about Java. I have a user-defined object class, student, which have 2 data members, name and id. And in another class, I have to declare that object[], (e.g. student stu[?];). However, I don't know the size of the object array. Is it possible to declare an object array but don't know the size? thank you.

+4  A: 

User ArrayList instead. It'll expand automatically as you add new elements. Later you can convert it to array, if you need.

As another option (not sure what exactly you want), you can declare Object[] field and not initialize it immediately.

Nikita Rybak
+1  A: 

As you have probably figured out by now, regular arrays in Java are immutable (in the sense that once you create an array of a certain size, that array's size cannot be changed), so in order to add items dynamically to an array, you need a mutable array. In Java, mutable arrays are implemented as the ArrayList class (java.util.ArrayList). A simple example of its use:

import java.util.ArrayList;

// Adds a student to the student array list.
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student());

The <Student> brackets (a feature called generics in Java) are optional; however, you should use them. Basically they restrict the type of object that you can store in the array list, so you don't end up storing String objects in an array full of Integer objects.

agentbanks217
Arrays in Java are not immutable. You can easily do `myArray[2] = 13`, thus changing the array. Perhaps you meant that their size cannot be changed?
Steven Schlansker
Yes that is what I meant, thanks for clarifying that. I'll clarify that in my answer.
agentbanks217
A: 

You could declare as: Student stu[]=null;, and create it with fixed size: stu[]=new Student[10] until you could know the size. If you have to use array.

卢声远 Shengyuan Lu