ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-06-28 06:31:08  阅读:206  来源: 互联网

标签:Java String 合并 second length result 数组 first


转自:

http://www.java265.com/JavaJingYan/202204/16502899232926.html

数组:

     数组(Array)是有序的元素序列。 [1] 若将有限个类型相同的变量的集合命名,那么这个名称为数组名。组成数组的各个变量称为数组的分量,也称为数组的元素,有时也称为下标变量。用于区分数组的各个元素的数字编号称为下标。数组是在程序设计中,为了处理方便, 把具有相同类型的若干元素按有序的形式组织起来的一种形式。 [1] 这些有序排列的同类数据元素的集合称为数组

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

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

方式一、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;
      } 

标签:Java,String,合并,second,length,result,数组,first
来源: https://www.cnblogs.com/java265/p/16403580.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有