A
Antony Sequeira
Hi
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 [])
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
(I originally posted this to comp.lang.java, but did not get much info)
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 [])
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
(I originally posted this to comp.lang.java, but did not get much info)