[concurrency-interest] [HS] why creation of array of parametrized type is unsafe

Joshua Bloch josh at bloch.us
Fri Nov 10 00:05:35 EST 2006


Dhanji,

No, collections are very different.  You can create a collections whose
elements are of a non-reified type:

   List<List<String>> lls = new ArrayList<List<String>>();

As you know, the array analogue is illegal:

    List<String>[] als = new List<String>[SIZE];

It is, however, the case that you don't get exceptions at run time is you
insert an element of the wrong type (unless you're using a checked
collection). One way to look at this is that Collections give you static
type safety but not runtime, and arrays give you runtime type safety but not
static.

        Josh

On 11/9/06, Dhanji R. Prasanna <dhanji at gmail.com> wrote:
>
> A similar problem exists with parameterized collections--at runtime I can
> add objects not of a reified type via reflection (unless using a checkedSet
> or list..which throws CCE).
> Is this true?
>
> On 11/10/06, Joshua Bloch <josh at bloch.us> wrote:
> >
> > Rémi,
> >
> > Because the the array that is created is generally *not* an array of T
> > (the type parameter), but of its bound.  Automatically generated casts at
> > the call site can fail.  Run this program (which compiles with a warning)
> > and you'll get the idea.  The program was written by Peter van der Ahe:
> >
> >
> >
> > public class GenericVarargs {
> >    static <T> T[] m1(T t1, T t2) {
> >        return m2(t1, t2);
> >    }
> >    static <T> T[] m2(T... args) {
> >        return args;
> >    }
> >    public static void main(String... args) {
> >        String[] strings = m1("bad", "karma");
> >    }
> > }
> >
> >
> >
> > On 11/9/06, Rémi Forax < forax at univ-mlv.fr> wrote:
> > >
> > > It's a totally HS question, but i know that some Java gurus listen
> > > that
> > > list.
> > >
> > > It's perhaps a stupid question, but i don't see why array of
> > > parametrized type
> > > is unsafe.
> > >
> > > see my blog on that :
> > >
> > > http://weblogs.java.net/blog/forax/archive/2006/11/why_array_of_pa.html
> > >
> > > Rémi
> > >
> > > _______________________________________________
> > > Concurrency-interest mailing list
> > > Concurrency-interest at altair.cs.oswego.edu
> > > http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
> > >
> >
> >
> > _______________________________________________
> > Concurrency-interest mailing list
> > Concurrency-interest at altair.cs.oswego.edu
> > http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
> >
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20061109/93fa6f93/attachment.html 


More information about the Concurrency-interest mailing list