How to create a variable-sized array in Java?

Asked

Viewed 141 times

-1

I am trying to perform an exercise in Java that creates an A vector and adds even and odd values in 2 vectors, B and C, respectively. However, I am required to declare the size of these vectors before using them, so that there are empty positions in memory. For example:

    int[] A = new int[10];  

    for (int i = 0; i < A.length; i++){
        System.out.printf("Digite um valor para A[%d]: ", i);
        A[i] = scan.nextInt();
    }

    int[] B = new int[A.length];
    int[] C = new int[A.length];

    for (int i = 0; i < A.length; i++){
        if (A[i] % 2 == 0){
            B[i] = A[i];
        } else{
            C[i] = A[i];
        }
    }

    System.out.println();

    System.out.println("Você digitou os seguintes valores pares: ");
    for (int i = 0; i < B.length; i++){
        if (B[i] != 0){
            System.out.printf("%d ", B[i]);
        }
    }

    System.out.println();

    System.out.println("Você digitou os seguintes valores ímpares: ");
    for (int i = 0; i < C.length; i++){
        if (C[i] != 0){
            System.out.printf("%d ", C[i]);
        }
    }

I wonder if there is any way to create a vector without an initial size limit, which adds the elements as needed, without leaving empty positions in memory.

1 answer

0


No, arrays have a fixed size. If you want a flexible structure, without having to specify the size, and that grows as needed, you should use ArrayList.

int[] numeros = new int[10];
for (int i = 0; i < numeros.length; i++) {
    System.out.printf("Digite um valor para A[%d]: ", i);
    numeros[i] = scan.nextInt();
}

List<Integer> pares = new ArrayList<>();
List<Integer> impares = new ArrayList<>();
for (int i = 0; i < numeros.length; i++) {
    if (numeros[i] % 2 == 0) {
        pares.add(numeros[i]);
    } else {
        impares.add(numeros[i]);
    }
}

System.out.println("\nVocê digitou os seguintes valores pares: ");
for (int n : pares) {
    System.out.printf("%d ", n);
}

System.out.println("\nVocê digitou os seguintes valores ímpares: ");
for (int n : impares) {
    System.out.printf("%d ", n);
}

Note also that I used \n to skip a line instead of a println emptiness.

But remember that with ArrayList you only gain the flexibility of not having to define the size, as it grows as needed. But this does not prevent waste, as it internally allocates an array with more space than it needs, and when this array is full, it reallocates another larger one (also with excess space), and so on. So don’t kid yourself that you’re "saving" space or anything like that.

There is also the question of auto-Boxing and auto-Unboxing, by converting from int for Integer and vice versa, that despite being "transparent" for the programmer, has its cost there.


But if you have to use array, a slightly better solution would be to store the amount of even and odd numbers. There will still be waste, but it’s better than testing if the number is zero (because if the user types zero, you don’t count as an even number?):

int[] numeros = new int[10];
for (int i = 0; i < numeros.length; i++) {
    System.out.printf("Digite um valor para A[%d]: ", i);
    numeros[i] = scan.nextInt();
}

int[] pares = new int[numeros.length];
int[] impares = new int[numeros.length];
int indicePar = 0, indiceImpar = 0;
for (int i = 0; i < numeros.length; i++) {
    if (numeros[i] % 2 == 0) {
        pares[indicePar] = numeros[i];
        indicePar++;
    } else {
        impares[indiceImpar] = numeros[i];
        indiceImpar++;
    }
}

System.out.println("\nVocê digitou os seguintes valores pares: ");
for (int i = 0; i < indicePar; i++) {
    System.out.printf("%d ", pares[i]);
}

System.out.println("\nVocê digitou os seguintes valores ímpares: ");
for (int i = 0; i < indiceImpar; i++) {
    System.out.printf("%d ", impares[i]);
}
  • Your first solution is exactly what I was looking for. Thank you very much!

  • But I was testing here my for using Arraylist and saw that it only accepts the loop in this format : for (int n : pairs) { System.out.printf("%d ", n); }

  • It doesn’t work using the for the way I was asking the question?

  • @Matheuscavalcante Com ArrayList would have to be: for (int i = 0; i < pares.size(); i++) { System.out.printf("%d ", pares.get(i)); } - but if you just want to iterate for the values, I think for (int n: pares) more succinct and direct

  • I get it, thank you!

Browser other questions tagged

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