How to use links in Java?

I want to use the Java link, but I don’t know how to do it! for example, in C ++ we write:

void sum(int& x)
{
    ...
}

but in Java the sign is a compiler error! help me understand Java links.

+8
source share
4 answers

Objects are passed by reference Objects are accessible by reference, but there is no way to create a link to a primitive value (bytes, short, long). You either need to create an object to wrap an integer, or use a single array of elements.

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 might work:

public int sum(int v){
   return ...;
}

or

public int sum(){
   return ...;
}

Update:

Additional / better description of object references:

Java . (, ). , java, (, ), , (, ) . , ( ) .

:

, i, .

void primitive(int i){
  i = 0;
}

, ref, .

 void reference(Object ref){
    ref = new Object();//points to new Object() only within this method
 }

,

void object(List l){
   l.add(new Object());//modifies the object instead of the reference
}

MyInt .

+9

Java ++-, - ++ -. , Java- .

int Java; .


: , @fatih, Java- . , , . , : Java ++, ++ pass-by-pointer.

+7

Java Pass By Value:

http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html http://javadude.com/articles/passbyvalue.htm http://javachannel.net/wiki/pmwiki.php/FAQ/PassingVariables ( )

, Java -, . , ?

public class App
{
    public static void main( String[] args )
    {
        Foo f1 = new Foo();
        doSomethingToFoo(f1);
        System.out.println(f1.bar); //Hey guess what, f1.bar is still 0 because JAVA IS PASS BY VALUE!!!
    }

    static void doSomethingToFoo(Foo f) {
        f = new Foo();
        f.bar = 99;
    }

    static class Foo {
        int bar = 0;
    }
}
+3

MutableInt Apache Commons , , .

MutableInt

void sum(MutableInt mx)
{
    int x = mx.getValue();
    x = ...
    mx.setValue(x);
}

...

MutableInt mx = new MutableInt(5);
sum(mx);
int result = mx.getValue();

, .

When creating an additional object, some overhead arises, just to provide a link, so the solution is not optimal, but in most cases you should be fine.

In general, it is always better to find a way to return the result from the method. Unfortunately, Java allows only one value to be returned this way.

0
source

All Articles