Maybe is a newbie question, but I don't understand why when I try to do something like Map<String, boolean>
my IDE screams saying "Syntax error on token "boolean", Dimensions expected after this token", but with Boolean it works perfect. Can anyone explain me why is it like that? Thanks in advance!!
Asked
Active
Viewed 4.7k times
26

raspayu
- 5,089
- 5
- 37
- 50
-
3The answer is in this more general question: [Why don't Generics support primitive types?](http://stackoverflow.com/questions/2721546/why-dont-generics-support-primitive-types) – Lukas Eder Jul 14 '11 at 08:40
-
1Most `Map
` can be replaced by a `Set – Jens Schauder Nov 10 '17 at 11:56`
3 Answers
44
Simply put: Java generics don't work with primitive type arguments, only classes. So in the same way, you can't use List<int>
, only List<Integer>
.
See the relevant Java Generics FAQ entry for more information.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
31
Use Boolean instead of boolean. Map can only contain objects and boolean is a primitive type not an object. Boolean is object wrapper of boolean.

Alvin
- 10,308
- 8
- 37
- 49
12
In addition to other responses, note that you can use Map<String, Boolean>
and use them almost as if it were Map<String, boolean>
. That is, you will be able to put
and get
boolean
s (primitive). Look up autoboxing for explanation why this works. There are some pitfalls of using autoboxing but in simple cases it should work.

Miserable Variable
- 28,432
- 15
- 72
- 133