• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to print only strings using generics when the list is having multiple types

 
Tanu Gulati
Ranch Hand
Posts: 113
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have the following code where i have many type values in the arrayListbut i wanted to print only those values which are strings using Generics ( i dont want to put any if condition in the while loop which checks for type) Is it possible ..i tried but below code did not help

 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think it is possible to do so.(I am not sure why you want to avoid if check, but better option would be to put instance of check in while loop using if)
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generics don't work that way. They will not "filter" elements of an existing List. In fact, when you compile this code, the compiler will generate warnings about "unchecked or unsafe operations." This is because you are misusing generics -- especially with the unchecked conversion:

List<String> list = arrayList;

Properly used, generics would prevent you from adding a non-String to the List in the first place.

See Java Tutorial - Generics, and especially note Type Erasure.
 
Tanu Gulati
Ranch Hand
Posts: 113
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i got it .....it is at the time of creation of a list when generics come to play but type check dont apply on already created list..

thanks
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tanu Gulati:
i got it .....it is at the time of creation of a list when generics come to play but type check dont apply on already created list..

thanks
Correct.

If you have a non-generic List you can use the instanceof operator to check whether you have a String when you retrieve the contents of the List, but a List of different class types looks like a recipe for disaster to me.
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly.

Stated differently:
Generics are a compile-time construct. They don't exist at run time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic