• Java如何将两个数组合并为一个数组呢?


    转自:

    Java如何将两个数组合并为一个数组呢?

    下文笔者讲述将两个数组合并的方法分享,如下所示:

    数组合并是我们日常经常遇见的需求,下文笔者将一一道来,如下所示
    

    方式一、apache-commons

    使用apache-commons中的ArrayUtils.addAll(Object[], Object[])
        
     String[] both = (String[]) ArrayUtils.addAll(first, second);
     static String[] concat(String[] first, String[] second) {}
     static <T> T[] concat(T[] first, T[] second) {}
    如果jdk不支持泛型,将T换成String
    

    方式二、System.arraycopy()

     static String[] concat(String[] a, String[] b) {
       String[] c= new String[a.length+b.length];
     
       System.arraycopy(a, 0, c, 0, a.length);
       System.arraycopy(b, 0, c, a.length, b.length);
     
       return c; 
     }
    

    方式三、Arrays.copyOf()

    在java6中,有一个方法Arrays.copyOf(),是一个泛型函数。我们可以利用它,写出更通用的合并方法

    public static <T> T[] concat(T[] first, T[] second) {
         T[] result = Arrays.copyOf(first, first.length + second.length);
         System.arraycopy(second, 0, result, first.length, second.length);
         return result;
    }
    
    public static <T> T[] concatAll(T[] first, T[]... rest) {
           int totalLength = first.length; 
           for (T[] array : rest) {
                 totalLength += array.length;
            }
       
            T[] result = Arrays.copyOf(first, totalLength);
            int offset = first.length;
      
           for (T[] array : rest) {
                System.arraycopy(array, 0, result, offset, array.length);
                offset += array.length;
           }
      
           return result;
      } 
    
    String[] both = concat(first, second);
    String[] more = concat(first, second, third, fourth);
    

    方式四、Array.newInstance

           private static <T> T[] concat(T[] a, T[] b) {
               final int alen = a.length;
               final int blen = b.length;
       
               if (alen == 0) {
                   return b;
               }
               if (blen == 0) {
                   return a;
               }
      
              final T[] result = (T[]) java.lang.reflect.Array.
                      newInstance(a.getClass().getComponentType(), alen + blen);
              System.arraycopy(a, 0, result, 0, alen);
              System.arraycopy(b, 0, result, alen, blen);
      
              return result;
          } 
  • 相关阅读:
    阶段六-Day01-Linux入门
    实际业务处理 Kafka 消息丢失、重复消费和顺序消费的问题
    ti代理商:好的ti代理商有哪些分销
    交流耐压试验目的
    redis集群之分片集群的原理和常用代理环境部署
    前端程序——猜数字游戏
    谈一谈关于Linux内核编译详解原理
    国科大图数据管理与分析课程项目gStore实验报告
    Python中的*args 和 **kwargs
    递归构建下拉树
  • 原文地址:https://blog.csdn.net/qq_25073223/article/details/125487866