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

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

问题描述

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

  public class Main {

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

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


(int i = 0; i blablubb [i] =over;
}
printArray(blablubb);


$ b public static void printArray(String [] arr){
for(String s:arr){
System.out.println(或多个);



$ b code


输出是:

  a 
b
c
超过
超过
超过

我假设第一个循环会覆盖数组中的字符串。所以在任何情况下输出都会结束。它似乎创建了一个值的副本,而不是创建一个参考。
我从未感觉到这一点。我做错了吗?有没有一个选项来创建一个引用呢?



//编辑:
似乎每个人都知道,除了我。我来自C背景,并没有足够的重视与C非常不同的术语引用。
幸运的是,我花了10分钟才弄明白这一点(这一次)。

$ p $ for(String s:$ b $ div class =h2_lin>解决方案

blablubb){
s =over;

code


$ b

等于这个:

  for(int i = 0; i  String s = blablubb [i]; 
s =over;



$ b $ p
$ b

这将创建一个临时字符串,其中包含数组中的值的副本,只有副本。这就是为什么 blablubb [] 内容保持不变。



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

  for(int i = 0; i  blablubb [i] =over; 
}

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

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


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);
        }
    }

}

The output is:

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?

//Edit: 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. Happily it took me just 10 minutes to figure this out (this time).

解决方案

This:

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

Is equal to this:

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

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按值或通过引用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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