My question is the following:
Its usual for Java code to have generic collections implemented like:
public class GenericCollection<T> {
private Object[] data;
public GenericCollection () {
// Backing array is a plain object array.
this.data = new Object[10];
}
@SuppressWarnings( "unchecked" )
public T get(int index) {
// And we just cast to appropriate type when needed.
return (T) this.data[index];
}
}
And used like this for example:
for (MyObject obj : genericCollection) {
obj.myObjectMethod();
}
Since the generic type of genericCollection is erased, the JVM doesn't seems to have a way to know that really inside 'data' array of genericCollection there are only MyObject instances, since the actual type of the array is Object, there could be a String in it, and calling 'myObjectMethod' on it would raise an exception.
So I'm assuming the JVM has to do some runtime checking gymnastics to know what really is inside that GenericCollection instance.
Now look at this implementation:
public class GenericCollection<T> {
private T[] data;
@SuppressWarnings( "unchecked" )
public GenericCollection ( Class<T> type ) {
// Create a type specific array.
this.data = (T[]) Array.newInstance( type, 10 );
}
public T get ( int index ) {
// No unsafe casts needed.
return this.data[index];
}
}
In this case we create a type specific array through reflection, so the JVM could infer there could be only be T objects inside that array in a given context, making the unsafe casts and possible expensive type checks redundant.
My question would be, given the things HotSpot can do, would it help in any way, performance-wise, to implement generic collections with a "proper" type specific backing array?
For example, does it helps HotSpot in removing unnecessary type checks or casts? Maybe possibly enabling it to more easily inline methods given it knows the backing array is of a specific type?