Modifying the Size of an Array at Run Time

0

I'm doing a java application, and I used netbeans to build the screen. On this screen I have a button that generates random numbers and places them inside an array, but I can not change its size when it is running.

What I did: I created a "tam" variable and assigned it to the vector

int vetor[] = new int[tam];

Then I created a button that updates the "tam" variable, defined in a field.

tam = Integer.parseInt(txtTamanho.getText());

But when you generate the vector again it continues with the same size.

    
asked by anonymous 03.10.2017 / 20:06

1 answer

3

The size of an array can not be changed after it is created. Two possibilities is to create a new array with the new size repopulate it with the old data (provided the new one is larger than the old one):

int[] newArray =  new int[oldArray.length];

for(int i = 0; i < oldArray.length; i++) {
    newArray[i] = oldArray[i];

}

Or use ArrayList , which is a flexible list with dynamic size.

ArrayList<Integer> lista = new ArrayList<>();
lista.add(1);
lista.add(2);
...
lista.add(n);
    
03.10.2017 / 20:12