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 use ArrayList:
...
No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular
ArrayList
essentially wraps an array and takes care of the logic for growing the array as required:Generally an
ArrayList
is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:
As others have said, you cannot change the size of an existing Java array.
ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:
[ ... ]
to index a list. You have to use theget(int)
andset(int, E)
methods.set(15, foo)
.add
,insert
andremove
methods.If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )
If you only really need an array that grows as you are initializing it, then the solution is something like this.
Arrays.copyOf()
method has many options to fix the problem with Array length increasing dynamically.Java API
Yes, we can do this way.
I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.
to add an element simply use:
In the (5,2) the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.