Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2006

Tip: Looking for answers? Try searching our database.

type safe array slice

Thread view: 
Antony Sequeira - 22 Mar 2006 01:01 GMT
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
KLeo - 22 Mar 2006 15:20 GMT
> I wanted to make a type safe array slice method (at least for single
> dimension arrays)
[quoted text clipped - 5 lines]
>         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 );
[quoted text clipped - 18 lines]
> Thanks,
> -Antony Sequeira


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.