Java Trick: Generic Array Converter
I had a problem of increasing size of the array. Of course I have to copy the array. But it is not easy with java Generics, because of the following problem:
the problem, aNew never is possible to cast to the type T because it is created as an Object type. I found a very good answer with help of the book: Core Java: Volume I—Fundamentals, Ninth Edition. It is easy with java reflections as shown in the line# 7 to 9. getClass().getComponentType() return the type of the array elements.
If you need you can make the method static by changing it signature to
public class ArrayUtils<T>{ public T[] resizeArray(T[] source, int offset){ int length = source.length+offset; Object[] aNew = new Object[length]; System.arraycopy(source, 0, aNew, 0, source.length); return (T[])aNew; } }Of course you can compile the ArrayUtils class, but you cannot use this method as shown in the following code segment:
public static void main(String[] args){ Integer[] ints = new Integer[2]; ints[0]=0; ints[1]=1; Integer[] newInts = new ArrayUtils<integer>().resizeArray(ints, 3); System.out.println(newInts.length); }Here the error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; at net.au.abc.abcid.test.ArrayCopyTest.main(ArrayCopyTest.java:9)
the problem, aNew never is possible to cast to the type T because it is created as an Object type. I found a very good answer with help of the book: Core Java: Volume I—Fundamentals, Ninth Edition. It is easy with java reflections as shown in the line# 7 to 9. getClass().getComponentType() return the type of the array elements.
import java.lang.reflect.Array; public class ArrayUtils<T>{ public T[] resizeArray(T[] source, int offset){ int length = source.length+offset; Class arrayClass = source.getClass(); Class elementType = arrayClass.getComponentType(); Object aNew = Array.newInstance(elementType, length); System.arraycopy(source, 0, aNew, 0, source.length); return (T[])aNew; } }
If you need you can make the method static by changing it signature to
public <t> T[] resizeArray(T[] source, int offset){.
Comments
Post a Comment
commented your blog