使用引用调用交换两个数字

发布于 2025-01-06 22:14:25 字数 521 浏览 1 评论 0原文

我们可以使用引用传递或引用调用来交换 Java 中的两个数字吗? 最近,当我在Java中遇到交换两个数字时,我

class Swap{
    int a,b;
    void getNos(){
        System.out.println("input nos");
        a = scan.nextInt();
        b = scan.nextInt(); // where scan is object of scanner class
    }
    void swap(){
        int temp;
        temp = this.a;
        this.a = thisb;
        this.b = this.a;
    }
}

在主方法中写道,我调用上述方法并采用两个整数ab,然后使用第二种方法我交换两个数字,但相对于对象本身......

这个程序或逻辑是否属于按引用传递? 这是正确的解决方案吗?

Can we swap two numbers in Java using pass by reference or call by reference?
Recently when I came across swapping two numbers in Java I wrote

class Swap{
    int a,b;
    void getNos(){
        System.out.println("input nos");
        a = scan.nextInt();
        b = scan.nextInt(); // where scan is object of scanner class
    }
    void swap(){
        int temp;
        temp = this.a;
        this.a = thisb;
        this.b = this.a;
    }
}

In the main method I call the above mentioned methods and take two integers a,b and then using the second method I swap the two numbers, but relative to the object itself....

Does this program or logic come under pass by reference?
And is this correct solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最偏执的依靠 2025-01-13 22:14:25

是和不是。 Java 从不通过引用传递,您的方法是一种解决方法。但是您创建一个类只是为了交换两个整数。相反,您可以创建一个 int 包装器并使用 pass 它,这样在不需要时可以将整数分开:

public class IntWrapper {
    public int value;
}

// Somewhere else
public void swap(IntWrapper a, IntWrapper b) {
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}

正如注释所示,我可能还不够清楚,所以让我详细说明一下。

通过引用传递是什么意思?这意味着当您将参数传递给方法时,您可以在该方法内更改原始参数本身。

例如,如果 Java 是按引用传递的,则以下代码将打印出 x = 1

public class Example {
    private static void bar(int y) {
        y = 10;
    }
    public static void main(String[] args) {
        int x = 1;
        bar(x);
        System.out.println("x = " + x);
    }
}

但正如我们所知,它会打印 0,因为参数传递给了 bar code> 方法是原始x 的副本,对它的任何赋值都不会影响x

下面的 C 程序也是如此:

static void bar(int y) {
    y = 1;
}
int main(int argc, char * argc[]) {
    int x = 0;
    bar(x);
    printf("x = %d\n", x);
}

如果我们想要更改 x 的值,我们就必须传递它的引用(地址),如下例所示,但即使在这种情况下,我们不会传递实际引用,而是传递引用的副本,通过取消引用它,我们将能够修改 x 的实际值。然而,直接赋值给引用不会改变引用本身,因为它是按值传递的:

static void bar(int &y) {
    *y = 1;
    y = NULL;
}
int main(int argc, char * argc[]) {
    int x = 0;
    int * px = &x;
    bar(px);
    printf("x = %d\n", x); // now it will print 1
    printf("px = %p\n", px); // this will still print the original address of x, not 0
}

因此传递变量的地址而不是变量本身可以解决 C 中的问题。但在 Java 中,因为我们没有地址,当我们想要给它赋值时,我们需要包装该变量。如果仅修改对象,我们就不会遇到这个问题,但同样,如果我们想分配给它,我们必须包装它,如第一个示例所示。这不仅适用于基元,也适用于对象,包括我刚才提到的那些包装对象。我将用一个(更长的)例子来展示它:

public class Wrapper {
    int value;
    private static changeValue(Wrapper w) {
        w.value = 1;
    }
    private static assignWrapper(Wrapper w) {
        w = new Wrapper();
        w.value = 2;
    }
    public static void main(String[] args) {
        Wrapper wrapper = new Wrapper();
        wrapper.value = 0;
        changeValue(wrapper);
        System.out.println("wrapper.value = " + wrapper.value); 
        // will print wrapper.value = 1
        assignWrapper(w);
        System.out.println("wrapper.value = " + wrapper.value); 
        // will still print wrapper.value = 1
    }
}

嗯,就是这样,我希望我说清楚了(并且没有犯太多错误)

Yes and no. Java never passes by reference, and your way is one workaround. But yet you create a class just to swap two integers. Instead, you can create an int wrapper and use pass it, this way the integer may be separated when not needed:

public class IntWrapper {
    public int value;
}

// Somewhere else
public void swap(IntWrapper a, IntWrapper b) {
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}

As the comments show, I might not have been clear enough, so let me elaborate a little bit.

What does passing by reference mean? It means that when you pass an argument to the method, you can change the original argument itself inside this method.

For example, if Java was pass-by-reference, the following code will print out x = 1:

public class Example {
    private static void bar(int y) {
        y = 10;
    }
    public static void main(String[] args) {
        int x = 1;
        bar(x);
        System.out.println("x = " + x);
    }
}

But as we know, it prints 0, since the argument passed to the bar method is a copy of the original x, and any assignment to it will not affect x.

The same goes with the following C program:

static void bar(int y) {
    y = 1;
}
int main(int argc, char * argc[]) {
    int x = 0;
    bar(x);
    printf("x = %d\n", x);
}

If we want to change the value of x, we will have to pass its reference (address), as in the following example, but even in this case, we will not pass the actual reference, but a copy of the reference, and by dereferencing it we will be able to modify the actual value of x. Yet, direct assignment to the reference will no change the reference itself, as it is passed by value:

static void bar(int &y) {
    *y = 1;
    y = NULL;
}
int main(int argc, char * argc[]) {
    int x = 0;
    int * px = &x;
    bar(px);
    printf("x = %d\n", x); // now it will print 1
    printf("px = %p\n", px); // this will still print the original address of x, not 0
}

So passing the address of the variable instead of the variable itself solves the problem in C. But in Java, since we don't have addresses, we need to wrap the variable when we want to assign to it. In case of only modifying the object, we don't have that problem, but again, if we want to assign to it, we have to wrap it, as in the first example. This apply not only for primitive, but also for objects, including those wrapper objects I've just mentioned. I will show it in one (longer) example:

public class Wrapper {
    int value;
    private static changeValue(Wrapper w) {
        w.value = 1;
    }
    private static assignWrapper(Wrapper w) {
        w = new Wrapper();
        w.value = 2;
    }
    public static void main(String[] args) {
        Wrapper wrapper = new Wrapper();
        wrapper.value = 0;
        changeValue(wrapper);
        System.out.println("wrapper.value = " + wrapper.value); 
        // will print wrapper.value = 1
        assignWrapper(w);
        System.out.println("wrapper.value = " + wrapper.value); 
        // will still print wrapper.value = 1
    }
}

Well, that's it, I hope I made it clear (and didn't make too much mistakes)

做个少女永远怀春 2025-01-13 22:14:25
import java.util.*;
public class Main
{
  int a,b;


void swap(Main ob)
{
    int tmp=ob.a;
    ob.a=ob.b;
    ob.b=tmp;
}

void get()
{
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter a and b: ");
    a=sc.nextInt();
    b=sc.nextInt();
}

public static void main(String[] args) {
    Main ob=new Main();
    ob.get();
    ob.swap(ob);
    System.out.println(ob.a+" "+ob.b);
}}
import java.util.*;
public class Main
{
  int a,b;


void swap(Main ob)
{
    int tmp=ob.a;
    ob.a=ob.b;
    ob.b=tmp;
}

void get()
{
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter a and b: ");
    a=sc.nextInt();
    b=sc.nextInt();
}

public static void main(String[] args) {
    Main ob=new Main();
    ob.get();
    ob.swap(ob);
    System.out.println(ob.a+" "+ob.b);
}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文