[英]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.