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.
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.
Use the clone method of the array. Clone methods create a new array of the same size.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With