Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing a boolean array in java

I have this code

public static Boolean freq[] = new Boolean[Global.iParameter[2]]; freq[Global.iParameter[2]] = false; 

could someone tell me what exactly i'm doing wrong here and how would i correct it? I just need to initialize all the array elements to Boolean false. thank you

like image 446
leba-lev Avatar asked Mar 02 '10 16:03

leba-lev


People also ask

How is a boolean array initialized in Java?

The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null.

How do you initialize a boolean in Java?

To display Boolean type, firstly take two variables and declare them as boolean. val1 = true; Now, use if statement to check and display the Boolean true value.

How do you create a boolean array?

A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.

How do you initialize a 2d boolean array in Java?

grid = new boolean[n][n]; Simply typing the above line of code would result in the creation of a (n x n) 2-D array with default values set to false. However, the complexity remains O(n^2) with or without the usage of 2 loops(nested).


1 Answers

I just need to initialize all the array elements to Boolean false.

Either use boolean[] instead so that all values defaults to false:

boolean[] array = new boolean[size]; 

Or use Arrays#fill() to fill the entire array with Boolean.FALSE:

Boolean[] array = new Boolean[size]; Arrays.fill(array, Boolean.FALSE); 

Also note that the array index is zero based. The freq[Global.iParameter[2]] = false; line as you've there would cause ArrayIndexOutOfBoundsException. To learn more about arrays in Java, consult this basic Oracle tutorial.

like image 168
BalusC Avatar answered Sep 25 '22 13:09

BalusC