Java for 按值或按引用循环 [英] Java for loop by value or by reference

查看:26
本文介绍了Java for 按值或按引用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中发现了一个问题.首先是代码:

I figured out a a problem in my Code. First the code:

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String[] blablubb = { "a", "b", "c" };

        for(String s : blablubb) {
            s = "over";
        }
        printArray(blablubb);


        for (int i = 0; i < blablubb.length; i++) {
            blablubb[i] = "over";
        }
        printArray(blablubb);

    }

    public static void printArray(String[] arr) {
        for( String s : arr ) {
            System.out.println(s);
        }
    }

}

输出为:

a
b
c
over
over
over

我假设第一个循环也会覆盖数组中的字符串.所以无论如何输出都会结束.它似乎创建了该值的副本,而不是创建了一个引用.我从来没有意识到这一点.我做错了吗?是否可以选择创建引用?

I assumed the first loop would also overwrite the String in the array. So the output would be over in any case. It seems it creates a copy of the value instead creating a reference. I never perceived this. Am I doing it wrong? Is there an option to create a reference instead?

//好像大家都知道,除了我.我来自 C 背景,并没有足够注意与 C 非常不同的术语参考.幸运的是,我只用了 10 分钟就搞清楚了(这次).

// Seems like everybody knows about that except me. I'm from C background and doesn't pay enough attention to the term reference which is very different to C. Fortunately it took me just 10 minutes to figure this out (this time).

推荐答案

这个:

for (String s : blablubb) {
     s = "over";
}

等于这个:

for (int i = 0; i < blablubb.length; i++) {
     String s = blablubb[i];
     s = "over";
}

这会创建一个临时字符串,其中包含数组中值的副本,您只需更改副本.这就是 blablubb[] 内容保持不变的原因.

This creates a temporary String with a copy of the value from array and you change only the copy. That's why blablubb[] content stays untouched.

如果您想更改数组中的值,只需使用您的第二个选项:

If you want to change values in the array, just use your second option:

for (int i = 0; i < blablubb.length; i++) {         
    blablubb[i] = "over";
}

顺便说一句,你可以只用一行打印一个数组:

And, by the way, you can print an array with just one line:

System.out.println(Arrays.toString(blablubb));

这篇关于Java for 按值或按引用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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