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.
Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.
Hence, there arise dynamic arrays in java in which entries can be added as the array increases its size as it is full. The size of the new array increases to double the size of the original array.
Java has built-in dynamic arrays. These are Vector, ArrayList, LinkedList and CopyOnWriteArrayList. ArrayList is a resizable array implementation of the List interface.
As you have probably figured out by now, regular arrays in Java are of fixed size (an array's size cannot be changed), so in order to add items dynamically to an array, you need a resizable array. In Java, resizable 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With