Dynamic array in Java

What I want to do is

...
int sum[];
...
for(int z.....){
   ...
   sum[z] = some_random_value;
   ...
}

But it gives an error when the line sum [Z] = ran; The variable sum may not have been initialized

I tried int sum [] = 0; Instead of int sum []; But even that is wrong (I'm basically a C programmer)

Solution

It's impossible to use dynamically sized arrays in Java - you have to know the size before declaring, or resize operations on arrays (which can be painful)

Instead, using ArrayList < integer >, if you need it as an array, you can convert it back

List<Integer> sum = new ArrayList<>();
for(int i = 0; i < upperBound; i++) {
    sum.add(i);
}
// necessary to convert back to Integer[]
Integer[] sumArray = sum.toArray(new Integer[0]);
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
分享
二维码
< <上一篇
下一篇>>