亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java實(shí)現(xiàn)把兩個(gè)數(shù)組合并為一個(gè)的方法總結(jié)

 更新時(shí)間:2017年12月07日 10:03:21   作者:jaycee110905  
這篇文章主要介紹了Java實(shí)現(xiàn)把兩個(gè)數(shù)組合并為一個(gè)的方法,結(jié)合實(shí)例形式總結(jié)分析了java常用的四種數(shù)組合并操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Java實(shí)現(xiàn)把兩個(gè)數(shù)組合并為一個(gè)的方法。分享給大家供大家參考,具體如下:

在Java中,如何把兩個(gè)String[]合并為一個(gè)?

看起來是一個(gè)很簡(jiǎn)單的問題。但是如何才能把代碼寫得高效簡(jiǎn)潔,卻還是值得思考的。這里介紹四種方法,請(qǐng)參考選用。

一、apache-commons

這是最簡(jiǎn)單的辦法。在apache-commons中,有一個(gè)ArrayUtils.addAll(Object[], Object[])方法,可以讓我們一行搞定:

String[] both = (String[]) ArrayUtils.addAll(first, second);

其它的都需要自己調(diào)用jdk中提供的方法,包裝一下。

為了方便,我將定義一個(gè)工具方法concat,可以把兩個(gè)數(shù)組合并在一起:

static String[] concat(String[] first, String[] second) {}

為了通用,在可能的情況下,我將使用泛型來定義,這樣不僅String[]可以使用,其它類型的數(shù)組也可以使用:

static <T> T[] concat(T[] first, T[] second) {}

當(dāng)然如果你的jdk不支持泛型,或者用不上,你可以手動(dòng)把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;
}

使用如下:

String[] both = concat(first, second);

三、Arrays.copyOf()

在java6中,有一個(gè)方法Arrays.copyOf(),是一個(gè)泛型函數(shù)。我們可以利用它,寫出更通用的合并方法:

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;
}

如果要合并多個(gè),可以這樣寫:

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

還可以使用Array.newInstance來生成數(shù)組:

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;
}

更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)組操作技巧總結(jié)》、《Java字符與字符串操作技巧總結(jié)》、《Java數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》及《Java操作DOM節(jié)點(diǎn)技巧總結(jié)

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論