How to create an array of generics?

M

Matteo

I have the following snippet of code using array of vectors:

Vector[] tmpArr = new Vector[n];
for(int j=0; j<n; j++)
{
tmpArr[j] = new Vector();
....
String str = ...
....
if (!tmpArr[j].contains(str))
tmpArr[j].add(str);
}

And I want to convert to generics:

Vector<String>[] tmpArr = new Vector<String>[n];
for(int j=0; j<n; j++)
{
tmpArr[j] = new Vector<String>();
....
String str = ....
....
if (!tmpArr[j].contains(str))
tmpArr[j].add(str);
}


But the first row gives me an error:
-->Generic array creation.

If I change it in
Vector<String>[] tmpArr = new Vector<String>[n];
(as I've seen in a pdf by G.Bracha talking aout collections)
it gives me the error:
-->cannot find symbol
-->method add(String)

in the
tmpArr[j].add(str);
row.

The only way it seems to work is
Vector<String>[] tmpArr = new Vector[n];
but it gives me the unchecked conversion warning.

How can I create an array of generics?

Thank you!
Matteo
 
J

John Davison

How can I create an array of generics?

Unfortunately, you can't. See here:
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

"...attempting to create an array object whose element type is a type
variable causes a compile-time error... Since type variables don't exist
at run time, there is no way to determine what the actual array type
would be."

I didn't know this either. I think this kind of stinks.

John Davison
Compass Engineering Group
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,796
Messages
2,569,645
Members
45,369
Latest member
Carmen32T6

Latest Threads

Top