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 - 25 Mar 2006 00:11 GMT
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)
Roedy Green - 25 Mar 2006 01:19 GMT
On Fri, 24 Mar 2006 15:11:55 -0800, Antony Sequeira
<myfullname@hotmail.com> wrote, quoted or indirectly quoted someone
who said :

>I wanted to make a type safe array slice method (at least for single
>dimension arrays)

have a look inside ArrayList to see how they handled these problems.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Thomas Hawtin - 25 Mar 2006 01:50 GMT
> I wanted to make a type safe array slice method (at least for single
> dimension arrays)
[quoted text clipped - 16 lines]
> the erased type Object[]
> 2. this does not work for array of primitives such as int []

Yes, it will do that. If you passed int.class, which has type
Class<Integer> to Array.newInstance, then casting the result to
Integer[] or even Object[] would fail.

If you want to handle primitive types as well, then you'd need to
replace T[] with T. Much the same as System.arraycopy does.

From 1.6, you should be able to use Arrays.copyOfRange.

> (I originally posted this to comp.lang.java, but did not get much info)

Probably because that newsgroup should have been deleted many years ago.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Roedy Green - 25 Mar 2006 05:50 GMT
On Sat, 25 Mar 2006 00:52:20 +0000, Thomas Hawtin
<usenet@tackline.plus.com> wrote, quoted or indirectly quoted someone
who said :

> From 1.6, you should be able to use Arrays.copyOfRange.

see http://mindprod.com/jgloss/array.html#COPYING
for sample code to copy arrays by four different techniques.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Hendrik Maryns - 27 Mar 2006 11:01 GMT
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
NotDashEscaped: You need GnuPG to verify this message

Antony Sequeira schreef:
> Hi
>
[quoted text clipped - 26 lines]
> Are there better solutions ?
> Do you see any other issues with the above code ?

I don't see any point in using the dim int array, when you can just use
length.  You need a one-dimensional array anyway.

A trick is to pass the type as a parameter to the method.

@SuppressWarnings("unchecked")
public static <T>  T [] arraySlice(T [] src, int offset, int
length,             Class<T> type) {
       T[] dst = (T []) java.lang.reflect.Array.newInstance(type, length);
        System.arraycopy(src,offset,dst,0,length);
        return dst;
}

-> You can't get rid of the warning except with
@SuppressWarnings("unchecked").
-> This still does not work with basic types.

See
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#How
%20do%20I%20generically%20create%20objects%20and%20arrays
?
or http://tinyurl.com/lef99 for a more thorough explanation.

HTH, H.
Signature

Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org

Thomas Hawtin - 27 Mar 2006 17:29 GMT
> A trick is to pass the type as a parameter to the method.
>
[quoted text clipped - 8 lines]
> -> You can't get rid of the warning except with
> @SuppressWarnings("unchecked").

You can if you pass the type of the array, instead of the component type:

    public static <T> T[] copyOfRange(
        T[] src, int offset, int length, Class<T[]> arrayClass
    ) {
        T[] dst = arrayClass.cast(java.lang.reflect.Array.newInstance(
                arrayClass.getComponentType(), length
        ));
        System.arraycopy(src, offset, dst, 0, length);
        return dst;
    }

Unfortunately, there isn't a particularly nice way from getting from
component type to array type. Again the problem is that the type of an
array of int is not Class<Integer[]>.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Hendrik Maryns - 28 Mar 2006 11:09 GMT
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
NotDashEscaped: You need GnuPG to verify this message

Thomas Hawtin schreef:

>> A trick is to pass the type as a parameter to the method.
>>
[quoted text clipped - 11 lines]
>
> You can if you pass the type of the array, instead of the component type:

<snip>

Interesting, thanks.

H.
Signature

Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org



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.