如何在 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 &标志是编译器错误!请帮助我理解 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;
}
修改方法内的引用,这只影响引用的内部副本,而不影响传递的值.
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屋!