在java中 如何使用,如何在Java中使用引用?

I want to use reference in Java but I don't know how!

for example in C++ we write:

void sum(int& x)

{

...

}

but in Java & sign is a compiler error!

please help me to understand references in Java.

解决方案

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] = ...;

}

or

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 ...;

}

or

public int sum(){

return ...;

}

Update:

Additional/Better description of object references:

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.

example:

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

}

Both the array and MyInt above are based on the modification of an object.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值