この記事では、2つの配列を1つに組み合わせるJava実装方法について説明します。次のように、参照のために共有してください。
Javaでは、2つの文字列を1つにマージする方法は?
それは非常に簡単な質問のようです。ただし、コードを効率的かつ簡潔に書く方法は、まだ考える価値があります。ここに4つの方法があります。選択を参照してください。
1。Apache-Commons
これが最も簡単な方法です。 Apache-Commonsには、 ArrayUtils.addAll(Object[], Object[])メソッドがあり、1つの行でそれを行うことができます。
String[] both = (String[]) ArrayUtils.addAll(first, second);
他の人は、JDKで提供された方法を自分で包み、包む必要があります。
便利なため、2つの配列を組み合わせることができるツールメソッドを定義します。
static String[] concat(String[] first, String[] second) {}
汎用のために、ジェネリックを使用して可能な限り定義し、文字列を使用するだけでなく、他のタイプの配列も使用できるようにします。
static <T> T[] concat(T[] first, T[] second) {}
もちろん、JDKがジェネリックをサポートしていないか、それを使用できない場合は、手動でtを文字列に変更できます。
2。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); c;}を返します次のように使用してください:
string []両方= concat(first、second);
3。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(2番目、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 [] vors = concat(first、second); string [] more = concat(first、second、3番目、4番目);
4。ARRAY.NEWINSTANCE
Array.newInstanceを使用して配列を生成することもできます。
private static <t> t [] concat(t [] a、t [] b){final int alen = a.length; final int blend = 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 + Blend); System.ArrayCopy(a、0、result、0、alen); System.ArrayCopy(b、0、result、alen、blend); return result;}Java関連のコンテンツの詳細については、このサイトのトピックをご覧ください:「Java Array操作スキルの要約」、「Javaキャラクターと文字列操作スキルの概要」、「Java数学的操作スキルの概要」、「Javaデータ構造とアルゴリズムに関するチュートリアル」、Java Operation Dom Nodeスキルの概要」
この記事がみんなのJavaプログラミングに役立つことを願っています。