search

Home  >  Q&A  >  body text

java - swap function

In the following code, the effect of exchanging two objects is not achieved
The output result is 3:4
Logically speaking, aren't all references in Java? You should be able to exchange objects directly!
Please explain my error and give a solution.
I hope the output result is 4:3
class Int
{

public int x;

}

public class Hello {


void swap(Int a,Int b)
{
    Int t=a;
    a=b;
    b=t;
}
public static void main(String[] args) {
    
    Hello hello=new Hello();
    Int a=new Int();
    Int b=new Int();
    a.x=3;
    b.x=4;
    hello.swap(a,b);
    System.out.println(a.x+":"+b.x);
}

}

某草草某草草2753 days ago707

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-05-17 10:07:49

    In the Java world, the input parameters of functions or methods are passed through value copy:

    原始类型(char,int,double等)都是通过直接拷贝变量值传参;
    对象类型都是通过引用拷贝(跟C++中引用不同)传参,通过该引用能够更改其指向的对象内部值,但是更改该引用值,仅对函数内部可见,函数外部的实参依然没有改变;
    

    Normally, java cannot implement it.
    And the inside of the int object private final int value; is final

    reply
    0
  • Cancelreply