Java : Best way to pass int by reference

后端 未结 7 2234
不知归路
不知归路 2020-11-28 05:36

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

7条回答
  •  旧时难觅i
    2020-11-28 06:09

    You can create a Reference class to wrap primitives:

    public class Ref
    {
        public T Value;
    
        public Ref(T value)
        {
            Value = value;
        }
    }
    

    Then you can create functions that take a Reference as a parameters:

    public class Utils
    {
        public static  void Swap(Ref t1, Ref t2)
        {
            T temp = t1.Value;
            t1.Value = t2.Value;
            t2.Value = temp;
        }
    }
    

    Usage:

    Ref x = 2;
    Ref 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
    

    Hope this helps.

提交回复
热议问题