If you use this syntax to declare a reference to a collection :Collection<?> c, you can assign it to anything that is a Collection. But assigning it to a Collection<Integer> reference will not allow u add anything to it, because it is a compiler only restriction, the type specification is being erased at runtime and if u could add something to it,the compiler could only verify the type from the declaration which is <?>(same thing like if u would say<? extends Object>) and that would mean u can add anything to it, which myght blow your application at runtime.
On Aug 24, 6:03 pm, Gary <[email protected]> wrote: > I do not understand this. > > I get no compiler complaints with this code: > > Collection<?> c = new ArrayList<Integer> > (10); // This code works > c = new ArrayList<Long> > (10); // This code > works > c = new ArrayList<String> > (10); // This code > works > > But when i try to add an Integer to the ArrayList I get complaints > form the compiler: > > Collection<?> c = new ArrayList<Integer> > (10); // This code works > c.add > (10); > // > Complains ??????????????? > c = new ArrayList<Long> > (10); // This code > works > c = new ArrayList<String> > (10); // Thiscode > works > > When i try this: > > Collection <Integer> c = new ArrayList<Integer>(10); > c.add > (10); > // > NO PROBLEM > > I thought i really understood this section up until this... > Can anyone tell me why the code will not work? > > Thanks, Gary --~--~---------~--~----~------------~-------~--~----~ To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/javaprogrammingwithpassion?hl=en -~----------~----~----~----~------~----~------~--~---
