type safe array slice

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Antony Sequeira

    #1

    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.refle ct.Array.newIns tance(src.getCl ass().getCompon entType() ,
    dim );
    System.arraycop y(src,offset,ds t,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

    #2
    Re: type safe array slice

    Antony Sequeira wrote:[color=blue]
    > 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 [])[/color]


    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
    [color=blue]
    > java.lang.refle ct.Array.newIns tance(src.getCl ass().getCompon entType() ,
    > dim );
    > System.arraycop y(src,offset,ds t,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
    >[/color]

    Comment

    Working...