Initializing a boolean array to false

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

I have this piece of code below. How do I initialize each element = false?

boolean[] seats = new boolean[10] 

I saw a similar question. But, the second line didnt make sense to me (Can you explain the 2nd line?).

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

回答1:

The default value for the elements in a boolean[] is false. You don't need to do anything.

The reason it's necessary for Boolean[] is because the default value is null.


To initialize to true, use the overload of Arrays.fill that accepts a boolean[].

boolean[] seats = new boolean[10]; Arrays.fill(seats, true); 

See it working online: ideone



回答2:

A boolean is initialized to false by default. So you need not to do anything specific here. When you create an array of booleans and don't initialize it all the elements will be be false.

how do I initialize it to True then?

Simple Arrays.fill(array, Boolean.TRUE);



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!