gnarlyninja gnarlyninja - 1 year ago 76
Java Question

String.equals with for each and for loop

String[] rgb = new String[3];

rgb[0] = Integer.toHexString(color.getRed());
rgb[1] = Integer.toHexString(color.getGreen());
rgb[2] = Integer.toHexString(color.getBlue());

for(String el : rgb)
el = "00";

for(int i = 0; i<3; i++)
rgb[i] = "00";

In the above code I evaluate each index based on weather or not each is = to zero.
yet it always runs false in the foreach loop and true when appropriate in the for loop.
can someone explain what is happening behind the scenes to make this happen?

i am not running them sequentially they are both there for demo purposes.

Answer Source

In your for-each loop, the String el is not actually a reference to the array rgb. It just holds the value of a given index in the array. Therefore, in this case, you have to use a normal for loop to modify the contents of the array; otherwise the contents of el are just overwritten each iteration of the loop.

A visual explanation:

String[] i = new String[]{"Hi", "Hello"};     <------- Contains two indexes.
for(String str : i){
    str = str + "!";

First iteration:

  • str is set to i[0], which has a value of "Hi"
  • str is set to str + "!", changing str to "Hi!"
  • end of braces; str is discarded

Second iteration:

  • str is set to i[1], which has a value of "Hello"
  • str is set to str + "!", changing str to "Hello!"
  • for loop ends; str is discarded

In no case are the values of i ever changed, because the values of str are separate references to Strings.

See this SO post about the concept of immutability(Wikipedia).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download