[英]Java : Best way to pass int by reference
我有一个解析函数,它解析来自字节缓冲区的编码长度,它将解析的长度作为int返回,并将索引作为整数arg作为缓冲区。 我希望函数根据它的解析来更新索引,即希望通过引用传递该索引。 在C中,我只传递一个int *
。 在Java中最干净的方法是什么? 我目前正在考虑传递索引arg。 作为int[]
,但它有点难看。
您可以尝试使用Apache Commons库中的org.apache.commons.lang.mutable.MutableInt
。 在语言本身没有直接的方法。
这在Java中是不可能的。 正如您所建议的那样,一种方法是传递int[]
。 另一个会有一个小类,例如包含int
IntHolder
。
您不能通过Java中的引用传递参数。
你可以做的是将整数值包装在一个可变对象中。 使用Apache Commons的MutableInt
是一个不错的选择。 另一种稍微混淆的方式是使用你建议的int[]
。 我不会使用它,因为不清楚为什么要在单细胞阵列中包装int
。
请注意, java.lang.Integer
是不可变的。
将字节缓冲区和索引包装到ByteBuffer对象中。 ByteBuffer封装了缓冲区+位置的概念,允许您从索引位置读取和写入,随着时间的推移,它会更新。
您可以使用java.util.concurrent.atomic.AtomicInteger
。
你可以设计这样的新类:
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;
您可以创建一个Reference类来包装基元:
public class Ref<T>
{
public T Value;
public Ref(T value)
{
Value = value;
}
}
然后,您可以创建将Reference作为参数的函数:
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
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.