Java:通过引用传递 int 的最佳方法
我有一个解析函数,它从字节缓冲区解析编码长度,它以 int 形式返回解析后的长度,并将缓冲区中的索引作为整数参数。我希望该函数根据解析的内容更新索引,即希望通过引用传递该索引。在 C 中,我只需传递一个 int *
。 在 Java 中执行此操作最干净的方法是什么? 我目前正在考虑传递索引参数。作为一个int[]
,但它有点难看。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以尝试使用 Apache Commons 库中的 org.apache.commons.lang.mutable.MutableInt 。语言本身没有直接的方法可以做到这一点。
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.这在 Java 中是不可能的。正如您所建议的,一种方法是传递
int[]
。另一种方法是有一个小类,例如包装int
的IntHolder
。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 anint
.在 Java 中不能通过引用传递参数。
您可以做的是将整数值包装在可变对象中。使用 Apache Commons 的
MutableInt
是一个不错的选择。另一种稍微混乱的方法是像您建议的那样使用int[]
。我不会使用它,因为不清楚为什么要将int
包装在单单元数组中。请注意,
java.lang.Integer
是不可变的。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 anint[]
like you suggested. I wouldn't use it as it is unclear as to why you are wrapping anint
in a single-celled array.Note that
java.lang.Integer
is immutable.您可以使用java.util.concurrent.atomic.AtomicInteger。
You can use
java.util.concurrent.atomic.AtomicInteger
.将字节缓冲区和索引包装到 ByteBuffer 对象。 ByteBuffer 封装了缓冲区+位置的概念,并允许您从索引位置读取和写入,索引位置会随着您的操作而更新。
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.
您可以像这样设计新类:
稍后您可以创建此类的对象:
然后您可以将
inte
作为参数传递给您想要传递整数变量的地方:因此用于更新整数值:
用于获取值:
You can design new class like this:
later you can create object of this class :
then you can pass
inte
as argument where you want to pass an integer variable:so for update the integer value:
for getting value:
您可以创建一个 Reference 类来包装基元:
然后您可以创建将 Reference 作为参数的函数:
用法:
希望这会有所帮助。
You can create a Reference class to wrap primitives:
Then you can create functions that take a Reference as a parameters:
Usage:
Hope this helps.