In this post, we discuss how to copy array of different types in Java.
1. Naive
We know that arrays are objects in Java but they are container object that holds values of a single type. So in order to cast T[]
array to an U[]
array, each member of the specified T[]
must be cast to a U
object. This is demonstrated below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.Arrays; class CopyArrays { /** * Copies the specified array * * @param <T> the class of the objects in the source array * @param <U> the class of the objects in the destination array * @param source the source array * @param dest the destination array * * @throws NullPointerException if original is null * @throws ArrayStoreException if an element copied from source is not of * a runtime type that can be stored in an array of class U */ public static <T,U> void copyArray(T[] source, U[] dest) { for (int i = 0; i < source.length; i++) dest[i] = (U) source[i]; } // Program to copy array of different types in Java public static void main(String args[]) { Number[] source = { 1, 2, 3, 4, 5 }; Integer[] dest = new Integer[source.length]; try { copyArray(source, dest); } catch (ArrayStoreException e) { e.printStackTrace(); } System.out.println(Arrays.toString(dest)); } } |
Output:
[1, 2, 3, 4, 5]
2. Arrays.copyOf()
Arrays
class provides copyOf()
method which is used to copy the specified array into a new array. It has an overloaded version where we can specify the Type
of resulting array. This is demonstated below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.Arrays; class CopyArrays { /** * Copies the specified array * * @param <T> the class of the objects in the original array * @param <U> the class of the objects in the returned array * @param source the array to be copied * @param newType the class of the copy to be returned * * @return a copy of the original array * * @throws NullPointerException if original is null * @throws ArrayStoreException if an element copied from original is not of * a runtime type that can be stored in an array of class newType */ public static <T, U> U[] copyArray(T[] source, Class<U[]> newType) { return Arrays.copyOf(source, source.length, newType); } // Program to copy array of different types in Java public static void main(String args[]) { Number[] source = { 1, 2, 3, 4, 5 }; try { Integer[] dest = copyArray(source, Integer[].class); System.out.println(Arrays.toString(dest)); } catch (ArrayStoreException e) { e.printStackTrace(); } } } |
Output:
[1, 2, 3, 4, 5]
Similar to copyOf()
method, Arrays
class also provide an overloaded version of copyOfRange()
where we can specify the Type
of resulting array.
Thanks for reading.
Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
Leave a Reply