Typhaon
Typhaon

Reputation: 1054

How to return a slice in Java

I am working on a JavaCard, so a SIM card that runs Java (or a subset of it: Java Embedded). Due to memory limitations I have an array that I reuse for multiple tasks.

I want a function to basically return a pointer to that array, with an offset, thus a slice. This way I can be sure that no part of that array will be overwritten by accident.

Pointers dont exactly exist in Java, but is there a way to return a part of an array without copying it?

Upvotes: 4

Views: 234

Answers (3)

Maarten Bodewes
Maarten Bodewes

Reputation: 94038

Yesno. As suggested, you can do this by using a wrapper class which internally points to the array. As class fields are stored in EEPROM you can use JCSystem.makeTransientByteArray to create a start / end offset in the array. Then you can create a cursor or a "position" a la Java ByteBuffer in the array as well if that's required.

Of course you'd need get methods for retrieving bytes, byte arrays or shorts from the slice. In the get method you can use an index or the cursor.

If you have a newer version of Java Card you may not have to implement this as there is a JC version of ByteBuffer implemented. You may want to mimic this if it is not available yet in your version of the Java Card API.

Upvotes: 0

RoToRa
RoToRa

Reputation: 38431

Pointers don't exactly exist in Java, but is there a way to return a part of an array without copying it?

Since objects don't seem to be a good idea in JavaCard instead you could return an array consisting of two elements containing the start index and length (or alternatively start and end index) of the slice.

Upvotes: 0

RoToRa
RoToRa

Reputation: 38431

No, this is not possible. Object (references) is the closest you can get to pointers in Java.

If this were regular Java, I would have suggested, to wrap the array in a List with Arrays.asList and then use the List method subList, which provides a view of a section of the list without copying its contents.

However If I read the JavaCard API reference correctly these aren't included. You could try write a simple version of those interfaces/classes/methods yourself.

Upvotes: 3

Related Questions