Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic array in java

Tags:

java

arrays

What i am trying to do is

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

But it gives an error at line sum[z]=ran; that variable sum might not have been initialized.

I tried int sum[] = 0; instead of int sum[]; but even that gave an error. (I am basically a C programmer)

like image 661
Daksh Shah Avatar asked Jul 30 '26 13:07

Daksh Shah


1 Answers

An array of dynamic size isn't possible in Java - you have to either know the size before you declare it, or do resizing operations on the array (which can be painful).

Instead, use an ArrayList<Integer>, and 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]); 
like image 173
Makoto Avatar answered Aug 02 '26 02:08

Makoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!