-1

I was trying to set all the elements to null in an array of a defined class. I have just learned the usage of a for-each loop, so I tried the following:

for(MyClass element:array){
    element=null;
}

however this did not work after compiling, and there is a warning "The value of the local variable element is not used". I tried a normal for loop instead and it worked as expected:

for(int i=0;i<array.length;i++){
    array[i]=null;                              
}

My question is that why didn't the for-each loop work? Do I have some misunderstanding regarding its usage?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Teee
  • 61
  • 5
  • 5
    Related: [Is Java “pass-by-reference” or “pass-by-value”?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – OH GOD SPIDERS May 02 '17 at 10:17
  • Element is only a reference to a certain object in your array. You are basically just setting this reference to null. If you add `System.out.println(element);` then you can see that `element`is null, but you can still printout the entire array after your for-each loop. – kkflf May 02 '17 at 10:20

3 Answers3

5

Consider you have the following example:

String array[] = {"Hello", "Java"};
for (String element : array) {
    element = null;
}

In fact, element is a variable which I can use in my loop and not the real element of my array, this is equivalent to:

String array[] = {"Hello", "Java"};
for (int i = 0; i < array.length; i++) {
    String element = array[i];
    element = null;
}

So, when you use element = null, this does not change the value of the array (array[i]).

Hope you get it.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Thank you for your answer, I understand it now. So does it mean that for-each loop cannot be used to manipulate the actual element of an array, and I have to use a normal for loop to do that? – Teee May 02 '17 at 10:30
  • @Teee you can't use element you can use `array[i] = null` but you have to use another index for example `int i = 0; for (String element : array) { array[i] = null; i++; }` – Youcef LAIDANI May 02 '17 at 10:34
  • Here's a concrete example of how you answering this question hurts my (and I assume others') efforts to help users. I'm looking for a duplicate for [this](https://stackoverflow.com/questions/45845680/array-input-only-seems-to-take-the-last-input) which is a simple error in the way they access an array with a foreach loop. The canonical duplicate I used to close _this_ question is similar but not good enough. However, both that post and this one showed up in my search, when only the canonical should have. Now my search results are diluted with irrelevant questions. – Sotirios Delimanolis Aug 23 '17 at 17:38
  • ok what did you mean by this comment @Sotirios Delimanolis, you want to delete this one also? you know, I will tell you a secret, I do bad things this days because of you i sware! you destroy me step by step, ok go ahead and delete all my answers you are free and better than me – Youcef LAIDANI Aug 23 '17 at 18:13
  • No. What I want is for you to stop answering questions that have clearly been asked before. Just vote to close them as duplicates. You've been around for a while, you've seen all these questions asked before. There's no reason to keep answering them. – Sotirios Delimanolis Aug 23 '17 at 18:14
  • This is not about being _better than you_. You have some good answers, I just find them unnecessary. You can always take those answers and migrate them to the canonical duplicates, if you're introducing new useful information. That's the appropriate action here. – Sotirios Delimanolis Aug 23 '17 at 18:15
1

For each is Read only, if you set the value of element, you don't change it in the array itself, only inside the loop! Example:

    public class MainClass {
        public static void main(String args[]) {
            int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            for(int x : nums) {
              System.out.print(x + " "); 
              x = x * 10; // no effect on nums
            }

            System.out.println();

            for(int x : nums) 
              System.out.print(x + " "); 

            System.out.println();
        }  
    }

Which prints:

1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10
Feconiz
  • 39
  • 9
  • Thank you for your answer, I understand it now. So if I want to manipulate the element of an array, I have to use a normal for loop? – Teee May 02 '17 at 10:38
  • @Teee yes that's correct! – Feconiz May 02 '17 at 10:45
  • @Teee Yes. An enhanced for-loop is syntactic sugar to make things easier, but it doesn't replace a normal for-loop fully. You shouldn't use an enhanced for loop just because it is an enhanced for-loop. – MC Emperor May 02 '17 at 10:47
1

A side note: if all you're looking to do is fill your array with null, you can avoid for loops of either variety altogether with

Java.util.Arrays.fill(array, null);

Of course you then miss the opportunity to learn a valuable lesson about the differences between for-each and regular for.

Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21