user1410223
user1410223

Reputation:

using System.arraycopy to Convert double[] to Double[] and Viceversa , Java

I need work with double[] array, but sometime I need to work with Double[]

private Double[] double_Double(double[] ddata) {
  Double[] Ddata = new Double[ddata.length];
  for (int i = 0; i < ddata.length; i++) {
    Ddata[i] = ddata[i];
  }
  return Ddata;
}
private double[] Double_double(Double[] Ddata) {
  double[] ddata = new double[Ddata.length];
  for (int i = 0; i < Ddata.length; i++) {
    ddata[i] = Ddata[i];
  }
  return ddata;
}

Can I to develop this with System.arraycopy?

private Double[] double_Double(double[] ddata) {
  Double[] Ddata = new Double[ddata.length];
  System.arraycopy(ddata, 0, Ddata, 0, Ddata.length);
  return Ddata;
}
private double[] Double_double(Double[] Ddata) {
  double[] ddata = new double[Ddata.length];
  System.arraycopy(Ddata, 0, ddata, 0, ddata.length);
  return ddata;
}

How do I convert Double[] to double[]? Not answers my question!

The problem to test this method is due to the fractional part is "infinite"....

Upvotes: 2

Views: 733

Answers (1)

Ankur Anand
Ankur Anand

Reputation: 3904

No You can't

arrayCopy is an native method which does the copy. Here is the native code.

JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos, 
                               jobject dst, jint dst_pos, jint length))  
  JVMWrapper("JVM_ArrayCopy");
  // Check if we have null pointers
  if (src == NULL || dst == NULL) {
    THROW(vmSymbols::java_lang_NullPointerException());
  }
  arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
  arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
  assert(Universe::is_heap(s), "JVM_ArrayCopy: src not an oop");
  assert(Universe::is_heap(d), "JVM_ArrayCopy: dst not an oop");
  // Do copy
  Klass::cast(s->klass())->copy_array(s, src_pos, d, dst_pos, length, thread);
JVM_END

so here you will get ArrayStoreException because primitive type double and Object Type DOUBLE unboxing and boxing doesn't happen automatically in arrayCopy.

Upvotes: 1

Related Questions