Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a dynamic object array in Java?

Tags:

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.

like image 737
Questions Avatar asked Oct 08 '10 03:10

Questions


People also ask

How do you declare a dynamic array?

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.

Can we create dynamic array in Java?

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.

What is a dynamic array in Java?

Java has built-in dynamic arrays. These are Vector, ArrayList, LinkedList and CopyOnWriteArrayList. ArrayList is a resizable array implementation of the List interface.


2 Answers

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.

like image 112
ab217 Avatar answered Sep 28 '22 05:09

ab217


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.

like image 38
Nikita Rybak Avatar answered Sep 28 '22 06:09

Nikita Rybak