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:
strseti[0], has value of"hi"strsetstr + "!", changingstr"hi!"- end of braces;
strdiscarded
second iteration:
strseti[1], has value of"hello"strsetstr + "!", changingstr"hello!"forloop ends;strdiscarded
in no case values of i ever changed, because values of str separate references strings.
Comments
Post a Comment