Giá trị mặc định
- Mảng
boolean[](primitive): mặc định tất cảfalse. - Mảng
Boolean[](wrapper): mặc định tất cảnull.
Khởi tạo với giá trị cụ thể
Dùng Arrays.fill(array, value) để gán cùng giá trị cho toàn bộ mảng.
Ví dụ
import java.util.Arrays;
public class BooleanArrayInitExample {
public static void main(String[] args) {
// Mảng wrapper Boolean[] – mặc định null
Boolean[] boolArray = new Boolean[5];
System.out.println("Mặc định (Boolean[]):");
for (Boolean b : boolArray) System.out.println(b); // null x5
// Gán tất cả = false
Arrays.fill(boolArray, Boolean.FALSE);
System.out.println("\nSau fill FALSE:");
for (Boolean b : boolArray) System.out.println(b); // false x5
// Gán tất cả = true
Arrays.fill(boolArray, Boolean.TRUE);
System.out.println("\nSau fill TRUE:");
for (Boolean b : boolArray) System.out.println(b); // true x5
// Mảng primitive boolean[] – mặc định false
boolean[] primArray = new boolean[3];
System.out.println("\nMặc định (boolean[]): " + Arrays.toString(primArray)); // [false, false, false]
}
}
Kết quả
Mặc định (Boolean[]):
null
null
null
null
null
Sau fill FALSE:
false
false
false
false
false
Sau fill TRUE:
true
true
true
true
true
Mặc định (boolean[]): [false, false, false]
Mẹo: Với mảng primitive, có thể dùng Arrays.setAll(array, i -> i % 2 == 0) (Java 8) để gán theo logic.