How to do Array of Generics???

M

Matteo

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

Vector[] tmpArr = new Vector[n];
for(int j=0; j<nCol; j++)
{
tmpArr[j] = new Vector();
....
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 gemves me an 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!




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

bilbo

That's correct, you cannot create an array of generics, unless the
element type is a raw type or unbounded wildcard instantiation of a
generic type. So for example

// concrete instantiation, is illegal
Vector<String>[] vectors = new Vector<String>[10];

// unbounded wildcard instantiation, is legal
Vector<?>[] vectors = new Vector<?>[10];

// raw type, legal
Vector[] vectors = new Vector[10];

There is a very nice explanation of why this restriction exists can be
found in the Java Generics FAQ.
http://www.langer.camelot.de/GenericsFAQ/FAQSections/ParameterizedTypes.html
Look for the question "Can I create an array whose component type is a
concrete instantiation of a parameterized type?", and subsequent
question, for an explanation of the restriction and workarounds.
 

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,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top