1

「first」と呼ばれる配列と「second」と呼ばれる別の配列があります。どちらの配列もバイト型で、サイズは 10 インデックスです。

次のように、2つの配列をバイト型の「3番目」と呼ばれる長さ2 * first.lengthの1つの配列にコピーしています。

byte[] third= new byte[2*first.length];
for(int i = 0; i<first.length;i++){
    System.arraycopy(first[i], 0, third[i], 0, first.length);
    }   
for(int i = 0; i<second.length;i++){
    System.arraycopy(second[i], 0, third[i], first.length, first.length);
    }

しかし、それはコピーではなく、例外をスローします: ArrayStoreException

ここで、型の不一致のために src 配列の要素を dest 配列に格納できなかった場合に、この例外がスローされることを読みました。しかし、私の配列はすべてバイト単位であるため、不一致はありません

問題は何ですか?

4

2 に答える 2

9

配列要素ではなく配列をSystem.arraycopy渡します。に最初の引数として渡すことによりfirst[i]、(が引数を受け入れると宣言されているため) に昇格される を渡します。したがって、ドキュメントのリストの最初の理由は次のとおりです。arraycopybytearraycopyObjectsrcByteArrayStoreException

...次のいずれかが true の場合、ArrayStoreExceptionがスローされ、宛先は変更されません。

引数はsrc、配列ではないオブジェクトを参照しています。

2 つの配列を 3 番目の配列にarraycopyコピーする方法は次のとおりです。byte[]

// Declarations for `first` and `second` for clarity
byte[] first = new byte[10];
byte[] second = new byte[10];
// ...presumably fill in `first` and `second` here...

// Copy to `third`
byte[] third = new byte[first.length + second.length];
System.arraycopy(first,  0, third, 0, first.length);
System.arraycopy(second, 0, third, first.length, second.length);
于 2013-05-08T15:37:33.117 に答える
2
System.arraycopy(first, 0, third, 0, first.length);
System.arraycopy(second, 0, third, first.length, second.length);
于 2013-05-08T15:37:53.940 に答える