It is not possible to create a vector with variable size. What you can do is dynamically vary the size of the vector that is created, as in C99.
Creating array varying in size
Example:
Test[] create(int size) {
return new Test[size];
}
The above code creates a new class vector Test
with the size passed by parameter. Then you can create this array of the size you need:
Test[] array1 = create(10);
Test[] array2 = create(20);
Test[] array3 = create(lerEntradaDoUsuario());
Cloning the array with new size
Although Java does not support resizing arrays, for reasons of memory usage efficiency, 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 class Arrays
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 previous example is interesting, but it is easier to use an implementation that already takes care of it properly.
As already exemplified in other answers, the ArrayList
can be used as a data structure of variable size.
Underneath the cloths, it does exactly what I did in the example above, that is, it has an internal vector that is resized when you add more elements than it supports at any given time.
Which vector in C does not have the set size?
– utluiz
@utluiz he’s probably talking about array set in runtime available on C99. Or you may be talking about pointers accessed as if they were arrays, less likely. Anyway, of course there is always a set size. https://en.wikipedia.org/wiki/Variable-length_array What in Java can be done directly.
– Maniero