Can not create vector with variable length. What you can do is to dynamically vary the size of the vector that is created, as in C99.
Creating array by varying size
Example:
Test[] create(int size) {
return new Test[size];
}
The above code creates a new vector of class Test
with the size passed by parameter. Soon you can create this vector of the size you need:
Test[] array1 = create(10);
Test[] array2 = create(20);
Test[] array3 = create(lerEntradaDoUsuario());
Cloning the array with a new size
Although Java does not support resizing arrays, because of efficiency in memory usage, the basic solution if you need to increase it is to make a copy of the current array in a new array of the desired size.
This is very simple using the Arrays
class of Java:
//cria o array inicial
Test[] array = new Test[10];
//coloca um elemento na primeira posição
array[0] = new Test();
array[0].nome = "Eu";
//imprime o tamanho atual do array
System.out.println(array.length);
//clona o array atual em um novo array com 20 posições
//atribuindo na mesma variável
array = Arrays.copyOf(array, 20);
//imprime o tamanho do novo array
System.out.println(array.length);
//imprime o valor do elemento para provar que ele ainda está lá
System.out.println(array[0].nome);
ArrayList
The above example is interesting, but it's easier to use an implementation that already takes care of that.
As already exemplified in other answers, ArrayList
can be used as a variable-length data structure.
Under the wipes, it does exactly what I did in the example above, that is, it has an inner vector that is resized when you add more elements than it supports at a given time.