简体   繁体   English

Java-字节对象的引用传递

[英]Java - Pass by Reference for the Byte object

I read some code here: Is Java "pass-by-reference" or "pass-by-value"? 我在这里阅读了一些代码: Java是“按引用传递”还是“按值传递”?

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. 我可以对Byte对象执行相同的操作吗? 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?! 如果我使用=赋值运算符,它似乎会执行new Byte()自动装箱?! and therefore the value is not passed back. 因此该值不会传回。

Any ideas? 有任何想法吗? Regards. 问候。

Byte is immutable, which means its value cannot be changed. Byte是不可变的,这意味着它的值不能更改。 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. 您可以使用MutableByte ,一个元素的byte / Byte数组或自定义类。

The previous answer is correct, but just to add - yes in this case the Byte object is passed by reference. 前面的答案是正确的,但是只是添加了-是的,在这种情况下,Byte对象是通过引用传递的。 However because the Byte object is immutable even though it is passed by reference there is no way to modify it. 但是,因为即使通过引用传递了Byte对象,它也是不可变的,所以无法对其进行修改。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM