Change the size of an array at runtime

Asked

Viewed 934 times

0

I’m making a java application, and I used netbeans to build the screen. On this screen I have a button that generates random numbers and puts them inside an array, but I can’t change the size of it when it’s 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 the vector again Gero it continues with the same size.

  • Impossible, the size of an array is immutable. What you can do is create a new one with the larger size and repopulate, or use Collections.

  • You won’t be looking for ArrayList<Integer> ?

  • I’d put it on the button: vetor = new double[tam]

  • Do you put these numbers in the vector for what purpose? What are you going to use this vector for?

  • This vector stores the value of the products I have, the size of the vector indicates the number of products

1 answer

2


The size of an array cannot be changed after it is created. Two possibilities is to create a new array with the new size repopulate it with the old data (as long as 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 and dynamic-sized list.

ArrayList<Integer> lista = new ArrayList<>();
lista.add(1);
lista.add(2);
...
lista.add(n);
  • Thanks, I’ll try using arraylist

Browser other questions tagged

You are not signed in. Login or sign up in order to post.