Skip to main content
  1. About
  2. For Teams
Asked
Modified 10 years ago
Viewed 85 times
1

I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and printed every element, it shows they are still 0s.

        for(int num:a) 
              num=1;

But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try failed? And why it works when i print them? Thanks~~~

        for(int num=0;num<a.length;num++) 
            a[num]=1;
        for(int n:a)
            System.out.println(n);
0

2 Answers 2

3

Your first loop declares a local variable which only exists inside that loop. Its value iterates over every value in the array. A new memory location is reserved temporarily and given the name "num". Changing contents of that memory location does not modify the values in the "a" array.
Your second loop explicitly accesses memory allocated for the array "a" and changes their contents.

Sign up to request clarification or add additional context in comments.

Comments

3

These loops are different. Both in functionality and operations.

The first one - an enhanced-for loop - is giving you each element in the array referenced by the variable a. It is not exposing anything for you to mutate, so assignments to a have no effect on the actual value in the array.

The second loop is simply going through all of the elements in the array, but you are directly working with the array itself at all times, so mutating the values is perfectly possible.

To put this in other terms:

  • The enhanced-for is going through the array, and providing you a value to use. That value, while originally provided by the array, has no connection to the array otherwise. Any modifications made to the value would not propagate to the array.

  • The alternative loop is only ever accessing the array contents directly, where it is perfectly possible to make modifications and reassignments to the array.

Thus, if you ever want to set the values of an array to anything other than their default value, then using the second approach is the way to go.

Or...you could use Java 8's Stream API and come up with something like this:

IntStream.iterate(1, (x) -> 1).limit(100).toArray()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.