You can not restore the contents of a position in an Array or a collection through foreach . You have to use the classic for for this.
Array , in a simplistic way, is stored in memory as follows:
-
Each of the items (values) assigned to Array are stored in memory locations.
Endereço Valor
#00010 "Portugues"
#00011 "matemática"
#00013 "história",
#00014 "física"
-
Each position of Array is assigned a memory location that stores not the value itself, but the address where its value was stored.
Endereço Valor indice
#00001 #00010 [0]
#00002 #00011 [1]
#00003 #00012 [2]
#00004 #00013 [3]
What the foreach variable curso
receives is the reference (address) where the value corresponding to the index in question is stored and not the position of the Array
When the condition curso.equals(cursoModificar)
is true, the variable curso
is (referenced) the address # 00010 .
The variable cursoNovo
also references a memory location, the one that was assigned to it when the method was called, eg # 00030 .
When you run the curso = cursoNovo;
line, curso
starts to reference the # 00030 address, the one where the "sciences" string is, however nothing has changed in Array . The position [0]
, which is stored at # 00001 , continues to reference the # 00010 address, which continues to save the String " Portuguese".
Confused? Maybe not if you can think of addresses instead of values.
Note: Address values are only indicative.