This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics " Watch "Generics " New topic
Author

Generics

Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 422
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 ??


OCPJP 6.0-81% | Preparing for OCWCD
http://www.certpal.com/blogs/cert-articles | http://sites.google.com/site/mostlyjava/scwcd |
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

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()...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 422
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

Joined: Aug 03, 2008
Posts: 9291
    
  17

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)...
 
jQuery in Action, 2nd edition
 
subject: Generics
 
Similar Threads
Generics doubt (? super String)
Collections-Getting error, using subList(fromIndex, toIndex) in List!
Using lists in a jsp
jtips
map object as a key and as a value