returns Object Array, so it is unknown what the type is.
It returns Object since it can also be an int if the class is Integer.TYPE (the class to represent the int primitive).
Matt, sometimes you cannot avoid warnings like these. Your case is one of those cases; you know that the Object returned is an array of T so the cast is in fact safe. The compiler can't verify though so that's why the warning is there. You can use the SuppressWarnings("unchecked") annotation. Keep it as local as possible:
By the way, you can move the creation of result outside the if-statement. No matter what value count has, you always call "Array.newInstance(clazz, count);". If count happens to be 0 then you just hard code that 0.
Ok, there is actually the case where the total array size would exceed Integer.MAX_VALUE so count wraps around and gets negative; in that case you may want to set count to Integer.MAX_VALUE itself.
Matt Cartwright wrote:I understand that introducing a new variable and suppress warnings on its creation will eliminate the need to supress warnings on the entire method.
Thing is that I don't know what the garbage collector makes out of that as this method will be used heavily with huge amount of data.
It won't make any difference. That variable goes out of scope right after this method, together with result. After this method has returned the only reference to the newly created array is the one you use in the calling method:
I know thta theoretically the GC will clean out the object once it has gone out of scope, but in real life and under heavy load it mostly is different.
An object never goes out of scope. Variables go out of scope. That may cause an object to lose its last active reference, thereby making the object eligible for garbage collection. As I said before, the two local variables will make no difference.