Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of a collection? [duplicate]

Tags:

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.

like image 685
Murali Avatar asked Jun 07 '10 19:06

Murali


People also ask

How do you create an array of collections in Java?

Creating an Array Of Objects In Java – An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.

Which method of an array creates a duplicate copy?

Use the clone method of the array. Clone methods create a new array of the same size.

Can arrays contain duplicates?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.


1 Answers

The simple answer: do not mix arrays with generics!

Use a list of hashsets:

ArrayList<HashSet<Integer>> rows = new ArrayList<HashSet<Integer>>(); 

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:

HashSet<?>[] rows = new HashSet<?>[9];  for (int i = 0; i < rows.length; ++i)     rows[i] = new HashSet<Integer>(); 

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:

((HashSet<Integer>)rows[0]).add(4); 

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 TIntHashSet class: it will solve your problem and you'll end up having faster code.

like image 166
Jack Avatar answered Oct 19 '22 23:10

Jack