Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring int[] Array without defining size?

Tags:

java

arrays

This is my code:

int[] primes = new int[25];

    for (int i = 2; i <= 100; i++)
    {
        for (int j = i; j > 0; j--)
        {
            int prime = i%j;
            if (prime == 0)
            {
                if ((j == i) || (j == 1))
                {
                    isPrime = true;
                }
                else
                {
                    isPrime = false;
                    break;
                }
            }
        }

        if (isPrime == true){
            primes[index] = i;
            index++;
        }
    }

As you can see, I'm writing prime numbers into array. I counted all the prime numbers that are within range 2-100, so I set array size to 25.

But let's say that I wouldn't know there are 25 prime numbers. Is there a way to create an array (any type of array) without defining the size? I tried this:

int[] primes = new int[0];

But it crashed.

like image 586
Guy Avatar asked Dec 12 '22 08:12

Guy


2 Answers

You can use List for unknown size of data (probably ArrayList will be the best solution for you).

like image 59
BobTheBuilder Avatar answered Dec 23 '22 17:12

BobTheBuilder


No; an array's size must be declared ahead of time. Try taking a look at the different implementations of List or Vector.

If in the end you absolutely need an array, you may create an array from your List.

like image 28
bstempi Avatar answered Dec 23 '22 17:12

bstempi