Search code examples
javaarraysmemorybyteobject-reference

storing an object reference in byte array


I have a byte array and an object reference.

    byte[] data = new byte[128];

    Block b = new Block();

I want to store reference b in last 2 (or 4) bytes of "data" array.

Kindly Note: I dont want to serialize the object and store in byte array. I need to store a pointer( reference) referencing to a new block.

EDIT

My Block class is as follows

    public class Block {
        byte[] data ;

        public Block(){
            data = new byte[128];
        }
}

Basically the data array will use 126 byte to store a String and last two( or 4) bytes to store reference to another block. Its kind of Link List.

I could have done it using a different definition of Block class [By including reference to Block in class itself].. But problem statement states the constraint that only last 2 bytes should be used as a reference to another block. from other post I came to know that in jvm(32-bit) a reference is of size 4 bytes. Hence I think it can be only done using last 4 bytes

Snippet from problem statement

the last 2 bytes of the block is used to point to the next block . Suppose if the file is of 8 block size, then the last 2 bytes of 4th block will point to 5th block and last 2 bytes of 5th block points to 6th block and so on.


Solution

  • Basically the data array will use 126 byte to store a String and last two( or 4) bytes to store reference to another block. Its kind of Link List.

    You can do this by storing a Block index.

    e.g

    // list of blocks so you can lookup any block using a 16-bit index.
    List<Block> blocks = new ArrayList<Block>();
    
    int indexInBlocksToNext = ...
    data[126] = (byte) (indexInBlocksToNext >> 8);
    data[127] = (byte) indexInBlocksToNext;
    

    I could have done it using a different definition of Block class [By including reference to Block in class itself].. But problem statement states the constraint that only last 2 bytes should be used as a reference to another block. from other post I came to know that in jvm(32-bit) a reference is of size 4 bytes. Hence I think it can be only done using last 4 bytes

    All 32-bit systems use 32-bit pointers or references. You can't places an reference in Java because there is no global way of referring to an object via a number. You can obtain where an object was in memory, but this location can change at any time.


    With Java 7 the minimum memory used before you can start is about 1.3 MB.

    $ java -mx1200k -version
    Error occurred during initialization of VM
    Too small initial heap for new size specified
    $ java -mx1300k -version
    java version "1.7.0_05"
    Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
    Java HotSpot(TM) 64-Bit Server VM (build 23.1-b03, mixed mode)
    

    This means you have used more than your budget of 1 MB before your program even starts.