Java for loop by value or by reference

前端 未结 6 795
忘了有多久
忘了有多久 2020-12-10 04:37

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

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
           


        
相关标签:
6条回答
  • 2020-12-10 05:10

    When you want to do a low level optimization, know how, you have to look inside Java code and inside byte-code either(compiled code)

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

    is equals with:

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

    and that's why the output as how it is.

    0 讨论(0)
  • 2020-12-10 05:13

    Your for(String s : blablubb) loop is equivalent to the following code:

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

    Hopefully, from this you can see that all you are doing is reassigning a different value to s without changing blablubb[i]. This explains the output you see.

    0 讨论(0)
  • 2020-12-10 05:17
    for(String s : StringArray)
    {
    }
    

    is like

    for(int i = 0; i < StringArray.length; i++)
    {
        String s = StringArray[i];
    }
    
    0 讨论(0)
  • 2020-12-10 05:20
     s = "over"; 
    

    just changes the reference of s and not the String in the array.

    blablubb[i] = "over";
    

    changes the value stored at ith location in the array

    0 讨论(0)
  • 2020-12-10 05:21

    The for-each loop don't modify the objects contained in the Collection of objects it's iterating over. It's passing the value not the reference.

    0 讨论(0)
  • 2020-12-10 05:34

    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));
    
    0 讨论(0)
提交回复
热议问题