如何在Java中使用引用? [英] How to use references in Java?
问题描述
我想在Java中使用引用,但我不知道如何!
例如我们写的C ++:
I want to use reference in Java but I don't know how! for example in C++ we write:
void sum(int& x)
{
...
}
但是在Java& sign是编译错误!
请帮我理解Java中的引用。
but in Java & sign is a compiler error! please help me to understand references in Java.
推荐答案
默认情况下通过引用传递对象通过引用访问对象,但无法创建对原始值(byte,short,int,long)的引用。您必须创建一个对象来包装整数或使用单个元素数组。
Objects are passed by reference by default Objects are accessed by reference, but there is no way to create a reference to a primitive value (byte, short,int, long). You either have to create an object to wrap the integer or use a single element array.
public void sum(int[] i){
i[0] = ...;
}
或
public void sum(MyInt i){
i.value = ...;
}
public class MyInt{
public int value;
}
对于您的示例,以下内容可能有效
for your example something like the following could work
public int sum(int v){
return ...;
}
或
public int sum(){
return ...;
}
更新:
对象引用的附加/更好描述:
Additional/Better description of object references:
始终通过引用访问Java对象。与原始类型一样,此引用按值传递(例如复制)。由于程序员可以在java中访问的所有内容都是通过复制它(引用,基元)来传递的,并且无法创建对基本类型的引用,因此对方法参数(引用,基元)的任何修改只会影响其中的本地副本。方法。
可以在方法中修改对象,因为引用的两个副本(本地和其他)仍然指向同一个对象实例。
Java Objects are always accessed by a reference. Like the primitive types this reference is passed by value (e.g. copied). Since everything a programmer can access in java is passed by copying it (references, primitives) and there is no way to create a reference to a primitive type, any modification to a method parameter (references, primitives) only affects the local copy within the method. Objects can be modified within a method since both copies of the reference (local and other) still point to the same object instance.
示例:
修改方法中的基元,这只影响i的内部副本而不是传递的值。
Modify a primitive within method, this only affects the internal copy of i and not the passed value.
void primitive(int i){
i = 0;
}
修改方法中的引用,这只影响ref的内部副本而不是传递的值。
Modify a reference within method, this only affects the internal copy of ref and not the passed value.
void reference(Object ref){
ref = new Object();//points to new Object() only within this method
}
修改一个全局可见的对象
Modify an object, visible globally
void object(List l){
l.add(new Object());//modifies the object instead of the reference
}
上面的数组和MyInt都基于对象的修改。
Both the array and MyInt above are based on the modification of an object.
这篇关于如何在Java中使用引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!