1

Why this code doesn't add "1" to array's values? (I have written it by "Enhanced For Loop"; when I wrote it with "old For", it worked.

public class EnhanceForLoop {
    public static void main(String[] args) {

            int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

            System.out.println("List before call addOne");
            printList(list);

            System.out.println("Calling addOne");
            addOne(list);

            System.out.println("List after call addOne");
            printList(list);
    }               

    public static void addOne(int[] list) {
        for (int val : list) {
            val = val + 1;
        }
    }

    public static void printList(int[] list) {
        System.out.println("index, value");
        for (int i = 0; i < list.length; i++) {
            System.out.println(i + ", " + list[i]);
        }
    }
}
2
  • 2
    From the for-each doc: "Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it." In short, use the for-each when you perform a read-only operation. Commented Mar 27, 2015 at 9:37
  • You have misunderstood the purpose of enhance for loop. Commented Mar 27, 2015 at 9:53

2 Answers 2

1

You are not increasing array values.Do

public static void addOne(int[] list){
     for(int i=0;i<list.length;i++){
                list[i] = list[i] + 1;
         }
}

Below statement

val = val + 1;   //will not increase array value it will increase val value
Sign up to request clarification or add additional context in comments.

8 Comments

user is trying by pass by value, not by reference. So, it wont increment. Just check it
Thank you. So, we cannot use "Enhanced For Loop" for increasing values of array, right?
@ViswanathD "Just check it" Yes, you should do that.
@Shirin we can use any iterating process, but the incrementation should be done on original field (list) not on passed by value.
@Shirin yes in your case val does not denote array reference
|
1

The value you are increasing is for the declared variable val, which is disconnected copy of array's currently iterating index variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.