zoukankan      html  css  js  c++  java
  • java数组合并

    import java.lang.reflect.Array;
    
    public class ArraysUtils {
    
        /**
         *@来源 org.apache.commons.lang
         *@apiNote把数组A和数组B合并到一个数组
         * */
        public static Object[] addArrays(Object[] A, Object[] B) {
            if (A == null) {
                return clone(B);
            } else if (B == null) {
                return clone(A);
            }
            Object[] joinedArray = (Object[]) Array.newInstance(A.getClass().getComponentType(), A.length + B.length);
            System.arraycopy(A, 0, joinedArray, 0, A.length);
            try {
                System.arraycopy(B, 0, joinedArray, A.length, B.length);
            } catch (ArrayStoreException ase) {
                //需要保证合并的对象类型相同
                final Class<?> type1 = A.getClass().getComponentType();
                final Class<?> type2 = B.getClass().getComponentType();
                if (!type1.isAssignableFrom(type2)) {
                    throw new IllegalArgumentException("Cannot store " + type2.getName() + " in an array of " + type1.getName());
                }
                throw ase; 
            }
            return joinedArray;
        }
    
        private static Object[] clone(Object[] array) {
            if (array == null) {
                return null;
            }
            return (Object[]) array.clone();
        }
        
        public static void main(String[] args) {
            Integer[] a = { 1, 2, 3, 4, 5 };
            Short[] b = { 9, 7, 8, 9 };
            Object[] addAll = addArrays(a, b);
            for (int i = 0; i < addAll.length; i++) {
                System.out.println(addAll[i]);
            }
        }
    }
  • 相关阅读:
    水洼,八连杀
    友链
    万能转换字符类型到int ,int到string,string到char or char *等等
    蓝桥杯模拟赛题
    2020 03 21
    2019 12 02 reading
    CentOS 7 定时计划任务设置
    xinted &telnet
    2019 12 02 section C one
    【暖*墟】#洛谷网课1.30# 树上问题
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/11431156.html
Copyright © 2011-2022 走看看