Copy Array of Different Types in Java

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:

Download   Run Code

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:

Download   Run Code

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

Notify of
avatar
wpDiscuz