How to combine two arrays of different types in Java

1 Answer

0 votes
public class MyClass {
    public static Object[] combineArrays(Object[] arr1, Object[] arr2) {
        int len1 = arr1.length;
        int len2 = arr2.length;
        Object[] result = new Object[len1 + len2];
    
        System.arraycopy(arr1, 0, result, 0, len1);
        System.arraycopy(arr2, 0, result, len1, len2);
    
        return result;
    }
    public static void main(String args[]) {
        String[] stringArray = {"java", "c", "c#", "c++"};
        Integer[] intArray = {1, 2, 3};
        
        Object[] combined = combineArrays(stringArray, intArray);
        
        for (Object obj : combined) {
            System.out.println(obj);
        }
    }
}




/*
run:

java
c
c#
c++
1
2
3

*/

 



answered Sep 15, 2023 by avibootz

Related questions

2 answers 262 views
1 answer 208 views
1 answer 127 views
2 answers 164 views
1 answer 165 views
1 answer 168 views
1 answer 209 views
...