0

I want to convert ArrayList in java to vector in c++. How can I do this?

Input: jobject input in c++, which is ArrayList in JAVA. Output: class named vector in c++;

//Find jclass 4 ArrayList, just test jposCommits and jnegCommits are instances of ArrayList

jclass cls_arraylist = env->FindClass("java/util/ArrayList");

//get element
jmethodID arraylist_get = env->GetMethodID(cls_arraylist, "get", "(I)Ljava/lang/Object;");
//get array size
jmethodID arraylist_size = env->GetMethodID(cls_arraylist,"size","()I");
//get the length of pos and neg commits
jint lenArrayList_byte32 = env->CallIntMethod(jobArrayList_byte32, arraylist_size);


vector<byte[]> retKeyV;

for (int i = 0; i < lenArrayList_byte32; ++i) {

    jobject joneKey = env->CallObjectMethod(jobArrayList_byte32, arraylist_get, i);

What can I do next

Jonathan Rosenne
  • 2,159
  • 17
  • 27
Felix LL
  • 133
  • 4

1 Answers1

0
    jbytearray joneKey = static_cast<jbytearray>(env->CallObjectMethod(jobArrayList_byte32, arraylist_get, i));
    // to be protected, check that the type matches your expectation
    jclass joneKey_class = env->GetObjectClass(joneKey);
    jclass byteArray_class = env->FindClass("[B");
    assert(env->IsInstanceOf(joneKey_class, byteArray_class));
    jlong joneKey_len = env->GetArrayLength(joneKey);
    assert(joneKey_len > 0);
    byte* coneKey = new byte[joneKey_len];
    retKeyV.append(coneKey);
    env->GetByteArrayRegion(joneKey, 0, joneKey_len, coneKey);
    env->DeleteLocalRef(byteArray_class); // see comment below
    env->DeleteLocalRef(joneKey_class);
    env->DeleteLocalRef(joneKey);
}

To reduce some unnecessary overhead, you can keep a global reference to byteArray_class and not repeat FindClass() every time. You can skip all IsInstance() check if you don't doubt that the input data is correct. But if you don't check, be prepared to crash if the data is not as you expect it.

Additional improvement could be to set capacity of retKeyV to lenArrayList_byte32 when the vector is created.

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307