I'm writing a class which has two ArrayList
fields. One is for containing custom objects. The other is for containing custom collection objects (which may also have these fields):
private ArrayList<SomeClass> myObjList; // Just objects
private ArrayList<SomeCollectionClass> myCollectionList; // Collections of objects
In order to implement the Collection<E>
interface, I wrote an iterator()
method:
public Iterator<SomeClass> iterator() { ... }
But as a convenience method I also started to write a deepIterator() to return Iterators
for each of the collections in myCollectionList
- a collection of Iterators
- and things got very messy very quickly:
public Iterator<SomeClass>[] deepIterator() {
int numIterators = this.myCollectionList.size();
Iterator<SomeClass>[] iters = (Iterator<SomeClass>[]) new Iterator<SomeClass>[numIterators]; // not allowed
for (int i = 0; i <= numIterators; i++) {
iters[i] = this.myCollectionList.get(i).iterator();
}
return iters;
}
and the compiler throws a "generic array creation"
error. I understand why this happens, what I don't understand is why:
public Iterator<SomeClass>[] deepIterator() {
int numIterators = this.myCollectionList.size();
Iterator<SomeClass>[] iters = (Iterator<SomeClass>[])(Array.newInstance(Iterator.class, numIterators)); // allowed
for (int i = 0; i <= numIterators; i++) {
iters[i] = this.myCollectionList.get(i).iterator();
}
return iters;
}
compiles just fine. Can anyone explain? I'm not really concerned about the merits of array[]
versus some Collection<E>
class (ArrayList
or what have you) as the return type, I'm just mystified by that declare/instantiate/initialize line. Thanks in advance!