java - String.equals with for each and for loop -
this question has answer here:
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) { if(el.equals("0")) { el = "00"; } } for(int = 0; i<3; i++) { if(rgb[i].equals("0")) { rgb[i] = "00"; } }
in above code evaluate each index based on weather or not each = zero. yet runs false in foreach loop , true when appropriate in loop. can explain happening behind scenes make happen?
i not running them sequentially both there demo purposes.
in for-each
loop, string el
not reference array rgb
. holds value of given index in array. therefore, in case, have use normal for
loop modify contents of array; otherwise contents of el
overwritten each iteration of loop.
a visual explanation:
string[] = new string[]{"hi", "hello"}; <------- contains 2 indexes. for(string str : i){ str = str + "!"; }
first iteration:
str
seti[0]
, has value of"hi"
str
setstr + "!"
, changingstr
"hi!"
- end of braces;
str
discarded
second iteration:
str
seti[1]
, has value of"hello"
str
setstr + "!"
, changingstr
"hello!"
for
loop ends;str
discarded
in no case values of i
ever changed, because values of str
separate references strings.
Comments
Post a Comment