Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to copy array of different types in Java

2 Answers

0 votes
import java.util.Arrays;
 
public class MyClass
{
    public static <T, U> void CopyArray(T[] arr, U[] dest) {
        for (int i = 0; i < arr.length; i++) {
            dest[i] = (U)arr[i];
        }
    }
 
    public static void main(String[] args)
    {
        Number[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        Integer[] dest = new Integer[arr.length];
 
        try {
            CopyArray(arr, dest);
        } catch (ArrayStoreException ex) {
            System.out.println("Exception: " + ex);
        }
        
        System.out.println(Arrays.toString(dest));
    }
}
 
 
 
 
/*
run:
  
[1, 2, 3, 4, 5, 6, 7]
  
*/

 



answered Mar 21, 2023 by avibootz
0 votes
import java.util.Arrays;
 
public class MyClass
{
    public static <T, U> U[] CopyArray(T[] arr, Class<U[]> newType) {
        return Arrays.copyOf(arr, arr.length, newType);
    }
 
    public static void main(String[] args)
    {
        Number[] arr = { 1, 2, 3, 4, 5, 6, 7 };

        try {
            Integer[] dest = CopyArray(arr, Integer[].class);
            
            System.out.println(Arrays.toString(dest));
        } catch (ArrayStoreException ex) {
            System.out.println("Exception: " + ex);
        }
    }
}
 
 
 
 
/*
run:
  
[1, 2, 3, 4, 5, 6, 7]
  
*/

 



answered Mar 21, 2023 by avibootz

Related questions

1 answer 105 views
1 answer 97 views
1 answer 140 views
1 answer 147 views
1 answer 188 views
1 answer 230 views
...