Possible Duplicate:
What’s the reason I can’t create generic array types in Java?
HashSet<Integer>[] rows = new HashSet<Integer>[9];
gives me a compilation error: generic array creation.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The simple answer: do not mix arrays with generics!
Use a list of hashsets:
The problem here is that Java specification doesn’t allow you to declare an array of generics object.
A workaround of it is to use the wildcard, but you will lose the type-safety:
This, in your case, won’t create problems when you are going to check if an item is contained: you can easily do
rows[0].contains(4)but when adding new content you will be forced to cast the row to the right type and suppress the warning of unchecked cast itself:A side note: if you feel pioneer just download the Trove Collections framework that has a not-generics, highly optimized version of an integer hashset made to work with primitive type, I’m talking about the
TIntHashSetclass: it will solve your problem and you’ll end up having faster code.