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?
Yes, wrap it and use the Collections framework.
Then use List.toArray() when necessary, or just iterate over said List.
I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:
this assigns your array size to be the one entered at run time into x.
You set the number of elements to anything you want at the time you create it:
Then you can initialize the elements in a loop. I am guessing that this is what you need.
If you need to add or remove elements to the array after you create it, then you would have to use an
ArrayList
.In java array length is fixed.
You can use a List to hold the values and invoke the
toArray
method if needed See the following sample:Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).
Example:
Note: available since Java 8.
In Java Array Sizes are always of Fixed Length But there is way in which you can Dynamically increase the Size of the Array at Runtime Itself
This is the most "used" as well as preferred way to do it-
In the above code we are initializing a new temp[] array, and further using a for loop to initialize the contents of the temp with the contents of the original array ie. stck[]. And then again copying it back to the original one, giving us a new array of new SIZE.
No doubt it generates a CPU Overhead due to reinitializing an array using for loop repeatedly. But you can still use and implement it in your code. For the best practice use "Linked List" instead of Array, if you want the data to be stored dynamically in the memory, of variable length.
Here's a Real-Time Example based on Dynamic Stacks to INCREASE ARRAY SIZE at Run-Time
File-name: DStack.java
File-name: Exec.java
(with the main class)
Hope this solves your query.