Obtain a float[] view of a byte[] array

Benoit Seguin :

I have some binary objects as byte[] and I need to convert them to float[] before performing some computations on them.

My current approach is the following:

bytes[] binaryData;
float[] docVector = new float[vectorSize];
ByteBuffer.wrap(binaryData).asFloatBuffer().get(docVector);

This does work, but as far as I understand it creates a copy of the original array, is it possible to get a float array that is pointing at the same memory address of the binary array? In python and numpy one can for instance do the following to get a view of the same data in memory:

import numpy as np
binary_data = np.zeros(40, dtype=np.uint8)
float_array = binary_data.view(np.float32)
talex :

It is impossible in java.

Only way to do something similar is to us Flyweight pattern

EDIT

I used name "Flyweight" incorrectly (thanks to @AdrianShum). What I meant is class like this:

class FloatArray {
    byte[] buff;
    void set(int index, float value) { ... }
    float get(int index) { ... }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=103961&siteId=1