我有一个解析函数,从字节缓冲区中解析编码长度,并将解析的长度作为int返回,并以整数参数作为缓冲区的索引。我希望该函数根据其解析的结果更新索引,即想通过引用传递索引。在C语言中,我会使用指向
int
的指针来实现。
在Java中,最干净的方法是什么?
我目前正在考虑将索引参数作为int[]
传递,但这有点丑陋。int
的指针来实现。
在Java中,最干净的方法是什么?
我目前正在考虑将索引参数作为int[]
传递,但这有点丑陋。org.apache.commons.lang.mutable.MutableInt
。在语言本身中没有直接的方法来实现这一点。Java中不可能实现这一点。如你所提议的,一种方法是传递一个 int[]
。另一种方法是使用一个小类来包装一个 int
,例如 IntHolder
。
java.util.concurrent.atomic.AtomicInteger
类。在Java中,你不能通过引用传递参数。
你可以将整型值封装在可变对象中。使用Apache Commons的MutableInt
是一个不错的选择。另一种略微更加晦涩的方法是使用int[]
,就像你建议的那样。我不会使用它,因为不清楚为什么要把int
包装在单元素数组中。
请注意,java.lang.Integer
是不可变的。
将字节缓冲区和索引封装到ByteBuffer对象中。 ByteBuffer封装了缓冲区+位置的概念,允许您从索引位置读取和写入数据,并在操作时更新其位置。
您可以像这样设计新类:
public class Inte{
public int x=0;
}
Inte inte=new Inte();
那么,当您想传递一个整数变量时,您可以将inte
作为参数传递:
public void function(Inte inte) {
some code
}
如果要更新整数值:
inte.x=value;
获取值的方法:
Variable=inte.x;
public class Ref<T>
{
public T Value;
public Ref(T value)
{
Value = value;
}
}
public class Utils
{
public static <T> void Swap(Ref<T> t1, Ref<T> t2)
{
T temp = t1.Value;
t1.Value = t2.Value;
t2.Value = temp;
}
}
使用方法:
Ref<Integer> x = 2;
Ref<Integer> y = 9;
Utils.Swap(x, y);
System.out.println("x is now equal to " + x.Value + " and y is now equal to " + y.Value";
// Will print: x is now equal to 9 and y is now equal to 2
Integer
是不可变的。 - Yuval Adam