Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an int array filed with zeros in Java

Tags:

I want to create a 10 dimensional array that's filled with zeros. If I simply use int[] array = new int[10]; do I have a guarantee that all int's in the array are zeros?

like image 610
Christian Avatar asked Mar 22 '11 12:03

Christian


People also ask

How do you make an array of zeros in Java?

If all adjacent elements(i, i+1) in array are equal and total number of element in array is even then it's all element can be converted to zero. For example, if array elements are like {1, 1, 2, 2, 3, 3} then its all element is convertible into zero.

How do you set an int array to 0?

You can call it like this: //fixed arrays int a[10]; setValue(a, 0); //dynamic arrays int *d = new int[length]; setValue(d, length, 0);

Can we initialize array with 0 size in Java?

Java allows creating an array of size zero. If the number of elements in a Java array is zero, the array is said to be empty. In this case you will not be able to store any element in the array; therefore the array will be empty.

How do you fill an array with zeros?

Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.


2 Answers

int always has initial value of 0. so

new int[10] 

is enough.

for other values use Arrays utility class.

   int arrayDefaultedToTen[] = new int[100]; 

   Arrays.fill(arrayDefaultedToTen, 10);

this method fills the array (first arg) with 10 (second arg).

like image 173
Kerem Baydoğan Avatar answered Nov 17 '22 11:11

Kerem Baydoğan


Yes, but it's only one-dimensional, not ten.

like image 40
Vance Maverick Avatar answered Nov 17 '22 12:11

Vance Maverick