Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
Harikrishna Gorrepati
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, How can we assign list of different types(Date and String, Line# 14 and 16) to List<String> at Line #6..Line #6 should accept only String types know ??
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand the question properly. Generics is only a compile time thing. If you create a List like new ArrayList<String>(), then the compiler ensures that you only add String objects to this list. For the JVM new ArrayList<String>() is the same as new ArrayList()...
 
Harikrishna Gorrepati
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit Garg wrote:I don't understand the question properly. Generics is only a compile time thing. If you create a List like new ArrayList<String>(), then the compiler ensures that you only add String objects to this list. For the JVM new ArrayList<String>() is the same as new ArrayList()...

Hi Ankit, You gave the basic purpose of Generics. Let me change my question this way. On line 14 we added string to list. Online 15 we added int/Integer to list. On line 16 we added Date to list. We passed this complete non-generic list From line 18 to generic list at line 6. Line 6 should accept only string values know. With this code, line 8 returns different types
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right that type safety is broken here. That's why you'll get a warning when you assign a raw list to a typed list (i.e. at line 18 when you pass l1 to addData method)...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic