Can I pass a primitive type by reference in Java?

后端 未结 9 1750
粉色の甜心
粉色の甜心 2021-02-05 22:58

I would like to call a method which could potentially take on different versions, i.e. the same method for input parameters that are of type:

  • boolean
  • byte
9条回答
  •  情歌与酒
    2021-02-05 23:28

    The object types of primitive types in Java (Double, Integer, Boolean, etc) are, if I remember correctly, immutable. This means that you cannot change the original value inside a method they are passed into.

    There are two solutions to this. One is to make a wrapper type that holds the value. If all you are attempting to do is change the value or get a calculation from the value, you could have the method return the result for you. To take your examples:

    public byte getValue(byte theByte) {...}
    public short getValue(short theShort) {...}
    

    And you would call them by the following:

    Short s = 0;
    s = foo.getValue(s);
    

    or something similar. This allows you to mutate or change the value, and return the mutated value, which would allow something like the following:

    Short s = foo.getValue(10);
    

    Hope that helps.

提交回复
热议问题