471,316 Members | 1,114 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,316 software developers and data experts.

type safe array slice

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

Mar 22 '06 #1
1 8525
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

Mar 22 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Dave Bazell | last post: by
13 posts views Thread by J. J. Cale | last post: by
108 posts views Thread by Bryan Olson | last post: by
24 posts views Thread by RyanTaylor | last post: by
7 posts views Thread by RubyRedRick | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.