I have a class - xClass, that I want to load into an array of xClass so I the declaration:
xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();
However, I don't know if I will need 10. I may need 8 or 12 or any other number for that matter. I won't know until runtime. Can I change the number of elements in an array on the fly? If so, how?
You can do some thing
As other users say, you probably need an implementation of java.util.List.
If, for some reason, you finally need an array, you can do two things:
Use a List and then convert it to an array with myList.toArray()
Use an array of certain size. If you need more or less size, you can modify it with java.util.Arrays methods.
Best solution will depend on your problem ;)
Where you declare the myclass[] array as :
, simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.
It is a good practice get the amount you need to store first then initialize the array.
for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store. if you want a dynamic array you could use
ArrayList()
and useal.add();
function to keep adding, then you can transfer it to a fixed array.doing so is redundant but just to show you the idea,
ArrayList
can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same withList
andStack
Java Array sizes are fixed , You cannot make dynamic Arrays as that of in C++.
Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.