Skip to main content

Did I Miss Generic Array Creation?

Posted by dwalend on January 7, 2005 at 5:07 AM PST

While sweeping up sawdust before the latest release of JDigraph, I used -Xlint to spot remaining places where I have some things to clean up. I have just a handful to go. I'm having the most trouble with creating Arrays in collection-like classes. JDigraph is a generic efficient directed graph representation, so these arrays are everywhere. I've taken examples from

        HeapMember<Key,Value,Comp$gt;[] fibNodes = (HeapMember<Key,Value,Comp>[])Array.newInstance(HeapMember.class,size());

results in a waring from lint.

The first thing I tried didn't compile:

        //doesn't compile
        HeapMember<Key,Value,Comp>[] fibNodes = new HeapMember<Key,Value,Comp>[size()];

results in

jdigraph/v2/source/collection/net/walend/collection/ generic array creation
        HeapMember<Key,Value,Comp>[] fibNodes = new HeapMember<Key,Value,Comp>[size()];       

I tried dynamically creating the array using java.lang.reflect.Array:

        HeapMember<Key,Value,Comp>[] fibNodes = (HeapMember<Key,Value,Comp>[])Array.newInstance(HeapMember.class,size());

which gives me the warning from lint again.

/Users/dwalend/projects/opensource/jdigraph/v2/source/collection/net/walend/collection/ warning: [unchecked] unchecked cast
found   : java.lang.Object
required: net.walend.collection.HeapMember<Key,Value,Comp>[]
         HeapMember<Key,Value,Comp>[] fibNodes = (HeapMember<Key,Value,Comp>[])Array.newInstance(HeapMember.class,size());

I've tried doing other things, especially to the HeapMember.class argument, but haven't found a solution that compiles with no warnings.

Is there some bit of API I missed? Is there a good reason not to create arrays of generics? Or should I report a RFE to Sun asking them to add generic parameters to Array.newInstance()?



Related Topics >>


why not just

why not just do
[prettify]HeapMember&amp;lt;Key,Value,Comp&amp;gt;[] fibNodes = (HeapMember&amp;lt;Key,Value,Comp&amp;gt;[])new HeapMember[size()];[/prettify]
it will still have an unchecked cast, but at least it doesn't need to use reflection