Java – declare int [] array without defining size?

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 to an array I calculated all primes in the range of 2-100, so I set the array size to 25

But let's say I didn't know there were 25 primes Is there any way to create an array (any type of array) without defining the size? I tried this:

int[] primes = new int[0];

But it collapsed

Solution

You can use list for data of unknown size (perhaps ArrayList will be your best solution)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>