I read some code here: Is Java "pass-by-reference" or "pass-by-value"?

public void foo(Dog d)
{
  d.getName().equals("Max"); // true
  d.setName("Fifi");
}

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true

Can I perform the same with the Byte object. I am at this point in my code and wondering how to "set" the value of the byte object?

If i use the = assignment operator it seems to perform the new Byte() autoboxing?! and therefore the value is not passed back.

Any ideas? Regards.

有帮助吗?

解决方案

Byte is immutable, which means its value cannot be changed. Assigning to it won't work in your case, since that would simply rebind the reference (which won't propagate back to the caller).

You could use MutableByte, a one-element byte/Byte array, or a custom class.

其他提示

The previous answer is correct, but just to add - yes in this case the Byte object is passed by reference. However because the Byte object is immutable even though it is passed by reference there is no way to modify it.

To be more specific when you call a function the parameters into the function are passed by value, but when you pass an Object what you actually pass by value is a reference to that object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top