Java:为什么这种交换方法不起作用? [英] Java: Why does this swap method not work?

查看:121
本文介绍了Java:为什么这种交换方法不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public class Main {

    static void swap (Integer x, Integer y) {
        Integer t = x;
        x = y;
        y = t;
    }

    public static void main(String[] args) {
       Integer a = 1;
       Integer b = 2;
       swap(a, b);
       System.out.println("a=" + a + " b=" + b);
    } 
}

我希望它打印a = 2 b = 1 ,但它打印相反。显然交换方法不会交换a和b值。为什么?

I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?

推荐答案

这与整数的不变性无关;它与 Java是按值传递这一事实有关,该死! (没有恼火,只是文章的标题:p)

This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )

总结:你不能真正做到Java中的swap方法。你只需要自己做交换,无论你需要什么;这只是三行代码,所以不应该是一个很大的问题:)

To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)

    Thing tmp = a;
    a = b;
    b = tmp;

这篇关于Java:为什么这种交换方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆