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]);
            }
        }
    }
  • 相关阅读:
    调试SQL Server的存储过程及用户定义函数
    寻找 vb.net 事务处理高级编程 的代码!!
    解析Java类和对象的初始化过程
    SQL 安装进程被挂起!
    教你成为一个受欢迎的人
    final class作用
    微软反跨站脚本库
    pdf解析
    ce'shi测试微博
    淘宝架构变化
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/11431156.html
Copyright © 2011-2022 走看看