Re: type safe array slice



Antony Sequeira wrote:
I wanted to make a type safe array slice method (at least for single dimension arrays)
Here is what I have

public static <T> T [] arraySlice(T [] src, int offset, int length) {
int [] dim = new int [1];
dim[0] = length;
T[] dst;
dst = (T [])


T [] - "Type variables don’t exist at run time. This means that
they entail no performance overhead in either time nor space,
which is nice. Unfortunately, it also means that you can’t
reliably use them in casts."

,
Leonid

java.lang.reflect.Array.newInstance(src.getClass().getComponentType() , dim );
System.arraycopy(src,offset,dst,0,length);
return dst;
}

This has two problems
1. Eclipse gives a warning for the type cast (T []) , saying
Type safety: The cast from Object to T[] is actually checking against the erased type Object[] 2. this does not work for array of primitives such as int []

I am assuming this does provide type safe array slicing for single dimension arrays of non primitives.

My questions :
Is the above a reasonable thing to do ?
Are there better solutions ?
Do you see any other issues with the above code ?

Thanks,
-Antony Sequeira

.