• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Boolean type as String within generics

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this:



When I do this:


then it prints out:


I use generics, so I allow, that instead of the boolean-value a String-value can be inserted.

Now, when I do that:



then I get a classCastException because of my value (which is a string).

So I have to convert my String to boolean with:



but it does not work. I even get the same classcastexception:



I cannot use the class.getName()... as I get the same failure as above, when I use this method.

So how can I enforce a convert from String to Boolean within generics, when I know, that the value is a String?
[ December 02, 2008: Message edited by: nimo frey ]
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by nimo frey:

Now, when I do that:



then I get a classCastException because of my value (which is a string).


You shouldn't get a CCE here. get will return a Boolean which will be unboxed into a boolean. It works for me.

So I have to convert my String to boolean with:



but it does not work.[/QB]


This won't work because the get() is returning a Boolean and parseBoolean expects a String as an argument.

Originally posted by nimo frey:
So how can I enforce a convert from String to Boolean within generics, when I know, that the value is a String?


What are you trying to convert from String to Boolean ? There shouldn't be any need to do this.
[ December 02, 2008: Message edited by: Joanne Neal ]
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What did you mean when you said:

Originally posted by nimo frey:
I use generics, so I allow, that instead of the boolean-value a String-value can be inserted.


The way I interpret this sentence is that you are able to insert both Boolean and String objets as values in the Map, indicating that somehow you're circumventing the compile-time type checking mechanism. You should be getting type safety warnings if that's the case.
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay, it works now.

However, I have thought, that generics are not absolutely type-save.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generics are type-safe, as long as you don't suppress or ignore any warnings from the compiler.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic