It compiles successfully but it really doesn't provide and generic type protection at compile time. I can still add whatever I want to the list (Objects, Strings, Threads). Also the get() method of the newly created list still returns an object.
Obviously this is very different to:
List aList = new ArrayList<String>();
Here I am prevented from adding in the wrong objects and the get method retuns a String.
What is the point in adding the generic type to the reference and to the object as it seems to me (I am a newbie with generics) that the reference achieves everything. Are their any Collection methods which would be be affected by the first statement?
I think you mean to get the difference between #1: List alist = new ArrayList<String>();
and #2: List<String> alist = new ArrayList();
#1: List reference type alist is not type safe, whereas you are assigning reference to the typesafe object, but when you add to the alist, it gives you warning of unsafe operation. That is because reference type is not type safe.
#2: In this your reference type is type safe but you are assigning it to the ref of type unsafe ArrayList object, hence warning. But when you add to the list, it wont give you warning because you have type safe reference of List.
Note: Always look for the reference variable whether it is type safe of not. if not, using add() method gives compiler warning.
Hi Jared Folino. I've asked a similar question a couple of days ago. I am quite sure that there is no difference in these two declarations Moreover, I would say that besides from getting a couple of compiler warnings, you can always do without the generic parameter on the right hand side of such a declaration/instantiation. And why shouldn't you? What matters at compile time is the reference type and generics only exist at compile time. At runtime there is nothing like an ArrayList of Integers so writing new ArrayList() or new ArrayList<Integer>() should not make any difference (Ok, the compiler won't let you get away with List<String> list = new ArrayList<Integer>(); but it could ) So, to point it out, there is also no difference in these two declarations:in both cases you 'll end up with a type safe reference to an ArrayList-object.
At least, that's what I think. [ May 26, 2007: Message edited by: Sasha Ruehmkorf ]
Yeah when you factor in that generics only exist at compile time it does make a lot more sense.
When you think about it it seems like the only time you would need to declare the actual objects type is when you want added protection when the list reference uses the <? extends X> or <? super X> syntax. In these case I think that you would need to declare both?
I'm doing laundry! Look how clean this tiny ad is:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth