Reputation: 97
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?
Upvotes: 3
Views: 2791
Reputation: 420991
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:
See also:
Upvotes: 7
Reputation: 62864
Declaring an array is different than declaring ArrayList
. The ArrayList
is supposed to contain objects, while the array can contain primitives or (references to) objects.
Also, there is a difference between declaring an array of primitives and wrapper types.
When you declare the array with:
boolean[] B = new boolean[n];
all the elements will default to false
.
However, when you declare the array with:
Boolean[] B = new Boolean[n];
all the elements will default to null
.
Upvotes: 5