There are many, many questions I have with generics in Java, but this one I'm still confused about. I hope that my title appropriately conveys the question I have with this one line of code. This has been provided in text that I'm seeing but there is no explanation as to why it is done in this manner.
T[] result = (T[]) new Object[numberOfEntries];
Basically, this line is within a method of a generic Array Bag
that implements an interface. Here is the full method it is found in:
public class Set<T> implements SetInterface<T>{
... //more methods for this Array-Bag
public T[] toArray(){
T[] result = (T[]) new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++){
result[index] = setArray[index];
}
return result;
}
}
This method is used to return a given copy of an array. But I do not understand why result
is casted and assigned with the (T[])
before the new Object[numberOfEntries]
. I understand that, since this is a class created as Set<T>
, anything that <T>
is (set of Strings, set of ints, etc) with take the place of <T>
. But what is the purpose of calling it in this manner? Also, why is it a new Object
and not a new instance of the Set
class that this method is found within?
If anyone needs further explanation/code I'll be happy to provide that. But I think that this practice for assigning and casting items with generics is common but I do not understand the reasons behind it.