views:

113

answers:

4

I have a parsing function that parses an encoded length from a byte buffer, it returns the parsed length as an int, and takes an index into the buffer as an integer arg. I want the function to update the index according to what it's parsed, i.e. want to pass that index by reference. In C I'd just pass an int *. What's the cleanest way to do this in Java? I'm currently looking at passing the index arg. as an int[], but it's a bit ugly.

+5  A: 

You can try using org.apache.commons.lang.mutable.MutableInt from Apache Commons library. There is no direct way of doing this in the language itself.

doublep
Great answer, never knew the mutable package existed. Thanks, got it much cleaner now :)
fred basset
+1  A: 

You cannot pass arguments by reference in Java.

What you can do is wrap your integer value in a mutable object. Using Apache Commons' MutableInt is a good option. Another, slightly more obfuscated way, is to use an int[] like you suggested. I wouldn't use it as it is unclear as to why you are wrapping an int in a single-celled array.

Note that java.lang.Integer is immutable.

Yuval A
+1  A: 

This isn't possible in Java. As you've suggested one way is to pass an int[]. Another would be do have a little class e.g. IntHolder that wrapped an int.

mikej
+1  A: 

Wrap the byte buffer and index into a ByteBuffer object. A ByteBuffer encapsulates the concept of a buffer+position and allows you to read and write from the indexed position, which it updates as you go along.

John Kugelman
Exactly. Don't force Java to do it your way, do it the Java way.Java is not C. Attempts to make it act like C will always be ugly hacks.
Skip Head