An array of generic sets

C

Christoph

The following command is syntactically invalid according to the Java
compiler:

Set<Item>[][] itemSets = new HashSet<Item>[4][2];

(The error is "Cannot create a generic array of HashSet<Item>")

Is there a correct way to accomplish this? As clear from the code, I
need a 4x2 array of Sets, each of which is restricted to instances of
Item.
 
H

Hendrik Maryns

Christoph schreef:
The following command is syntactically invalid according to the Java
compiler:

Set<Item>[][] itemSets = new HashSet<Item>[4][2];

(The error is "Cannot create a generic array of HashSet<Item>")

Is there a correct way to accomplish this? As clear from the code, I
need a 4x2 array of Sets, each of which is restricted to instances of
Item.

Generics and arrays do not go well together. See
http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html.

Use List instead:

List<List<Set<Item>>> itemSets = new ArrayList<List<Set<Item>>>();

and make sure to initialize intermediate lists and sets.

If you want to use arrays anyway, you have to use an unchecked
conversion (again, see above reference for the reason why):

Set<Item>[][] itemSets = new HashSet[4][2];

This will cause a warning message which you can suppress with
@SuppressWarnings("unchecked").

HTH, H.
--
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

iD8DBQFHlHrse+7xMGD3itQRAlNmAJ0b6MpqCElPeZmCuv8vHf/RGtSQYwCaAkuu
ZnFvuw2flbcHjb+X+5w5scc=
=dh3y
-----END PGP SIGNATURE-----
 
C

Christoph

This URL has proved very informative:
http://java.sun.com/docs/books/tutorial/extra/generics/fineprint.html

"Type variables don't exist at run time. [...] The component type of
an array object may not be a type variable or a parameterized type,
unless it is an (unbounded) wildcard type.You can declare array types
whose element type is a type variable or a parameterized type, but not
array objects."

So this is the best I can do, really:

Set<Item>[][] itemSets = new HashSet[4][2];
 
C

Christoph

Whooops. I found the answer without seeing it had already been posted.
Thanks! :)

--Chris
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top