0

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.

Pwrcdr87
  • 835
  • 3
  • 11
  • 32
  • By the way this code is very wrong as if `T` is anything except `Object`, trying to assign the result of this `.toArray()` to an actual array type will always crash. I don't know where you got this code from but you shouldn't use it. – newacct Feb 11 '16 at 00:38

1 Answers1

1

Java doesn't allow you to create an array of generic in one step. Instead you have to create an array of the type the generic extends (in this case Object) and cast the type.

You need a T[] as this return type of the toArray() method.

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
  • I believe I understand. Of course, under the "Related" list to the right, I now see this thread: http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java?rq=1 which one of the answers describe the reasons for this also (of course, your response matches with this thread as well). Great info! – Pwrcdr87 Feb 07 '16 at 03:39