Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare array using Boolean or boolean

If I want to declare a boolean array, I used to do this:

boolean[] B = new boolean[n];

all the element in array is false

Why couldn't do this?

Boolean[] B = new Boolean[n];

I knew boolean is primitive type while Boolean is its wrapper class. Why it's not like you declare ArrayList, here you use wrapper class instead of primitive class?

like image 924
xy254 Avatar asked May 19 '26 11:05

xy254


1 Answers

The difference

A Boolean[] is an array of references to Boolean objects. This means that index i will always be one of the following

array[i] == null
array[i] == Boolean.TRUE
array[i] == Boolean.FALSE

A boolean[] on the other hand, is an array of primitives, which means that you'll always have one of

array[i] == true
array[i] == false

Comparing to ArrayList<Boolean>

Why it's not like you declare ArrayList, here you use wrapper class instead of primitive class?

This is because generics were not designed to handle primitives, so you're forced to use the boxed versions.

This might change in future versions of Java. Here's a writeup from Brian Goetz on the subject:

    State of the Specialization

See also:

  • Boolean vs boolean in Java
  • Why do people still use primitive types in Java?
like image 164
aioobe Avatar answered May 21 '26 00:05

aioobe



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!