2016-10-18 2 views
2
outputArray[w:lastIndex] = array[v:lastIndex] 

すでに初期化されている別のサブ配列にサブアレイをコピーしたいと思います。サブアレイを初期化された配列にコピーするJavaの方法

確認することができます任意の作り付けの機能があります:

1)コピーする要素の数が同じであるが。何がLHS上で行うことができるかどうか私は知らない

Arrays.copyOfRange(array,v,lastIndex+1) 

:それは私のような何かを行うことができますRHSでindexOutOfBoundException

を起こしていないことを 2)。

私はInteger Arrayを使う必要があります+私はそれが配列の目的を無視していることを知っています。

答えて

3

あなたはSystem.arraycopyを使用することができます。

System.arraycopy (sourceArray, sourceFirstIndex, outputArray, outputFirstIndex, numberOfElementsToCopy); 

それは、しかし、IndexOutOfBoundsExceptionは無効なパラメータを提供している投げるん。

私が正しくあなたの例ではパラメータを理解していれば、あなたのような何か必要があります:あなたはlastIndexの要素があまりにもコピーする場合は

System.arraycopy (array, v, outputArray, w, lastIndex - v); 

または

System.arraycopy (array, v, outputArray, w, lastIndex - v + 1); 

を。

1

多分fill機能を使用することができます。

+0

私はfill関数について全く知らなかった。ありがとう。知っておいてよかった。 – technazi

+0

あなたは幸福です – karelss

2

あなたは、両方の送信元と送信先のアレイに開始インデックスの引数を取るSystem#arraycopyを、使用することができます。

System.arraycopy(array, v, outputArray, w, lastIndex - v) 
0

ドキュメントhttps://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html

Adds all the elements of the given arrays into a new array. 

The new array contains all of the element of array1 followed by all of the elements array2. When an array is returned, it is always a new array. 

ArrayUtils.addAll(null, null)  = null 
ArrayUtils.addAll(array1, null) = cloned copy of array1 
ArrayUtils.addAll(null, array2) = cloned copy of array2 
ArrayUtils.addAll([], [])   = [] 
ArrayUtils.addAll([null], [null]) = [null, null] 
ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"] 

Parameters: 
array1 - the first array whose elements are added to the new array, may be null 
array2 - the second array whose elements are added to the new array, may be null 
Returns: 
The new array, null if both arrays are null. The type of the new array is the type of the first array, unless the first array is null, in which case the type is the same as the second array. 
Throws: 
IllegalArgumentException - if the array types are incompatible 

    [1]: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html 
からArrayUtilsライブラリーののaddAllメソッド

を使用することができます

+1

それは本当にエレガントにヌル要素を処理します。しかし、私が推測するように、apacheコモンズはオーバーヘッドになります。 – technazi

関連する問題