| Author |
Generics..
|
Preethi Dev
Ranch Hand
Joined: Sep 07, 2008
Posts: 265
|
|
hi, this is my own code. import java.util.*; class Plant{ public static void main(String args[]){ List<String> li=new ArrayList(); li.add(new Object());//error li.add(new String("c")); } } Here we are not allowed to add anything other than String,why we are not calling this as type safe collection? what is the difference between List<String> li=new ArrayList(); and List<String> li=new ArrayList<String>();? please someone clear this.. thanks Preetha
|
 |
Preethi Dev
Ranch Hand
Joined: Sep 07, 2008
Posts: 265
|
|
|
if this has been discussed already...please someone give me the link.
|
 |
Shwetha Sharma
Ranch Hand
Joined: Jun 01, 2008
Posts: 34
|
|
Since the type safe checking is made at compile time only so List<String> li=new ArrayList(); and List<String> li=new ArrayList<String>(); works the same way i.e.they allow only string to be added to the list. Adding anything other than String will give a compile wrror in both cases. What actually the li contains ,whether an arrayList() or ArrayList<String>() is a runtime time issue and at Runtime due to type erasure ArrayList<String>()also becomes ArrayList()so I think there is no difference between them. Lets see what others have to say for this.
|
SCJP6:80%, OCWCD 88 %
|
 |
Amit Ghorpade
Bartender
Joined: Jun 06, 2007
Posts: 2561
|
|
|
"Shweta S Sharma S" please check your private messages for an important administrative matter. You can see them by clicking the My Private Messages link above.
|
SCJP, SCWCD.
|Asking Good Questions|
|
 |
Harvinder Thakur
Ranch Hand
Joined: Jun 10, 2008
Posts: 231
|
|
Originally posted by Preetha Arun: Here we are not allowed to add anything other than String,why we are not calling this as type safe collection? what is the difference between List<String> li=new ArrayList(); and List<String> li=new ArrayList<String>();? please someone clear this..
List<String> li=new ArrayList(); is a type safe collection. List<String> li=new ArrayList<String>(); is also a type safe collection. There is no difference in the above two statements as far as enforcing type safety is concerned. I had explained this in a similar post before with an example. Let me try once again. List<String> li = new ArrayList(); is type safe but on slightly modifying the code above we can see the difference imagine you were passed the ArrayList al by some other method and you assign it to li then you cannot guarantee that the ArrayList passed contains only Strings. e.g.
|
thanks
Harvinder
|
 |
 |
|
|
subject: Generics..
|
|
|