I think the code below will make my question clear. If they both pass by value, why are they different.
C# below:
static void Main(string[] args)
{
var list = new List<int> {1, 2, 3,};
ChangeVars(list);
foreach (var i in list)
{
Console.WriteLine(i);
}
Console.Read();
}
private static void ChangeVars(List<int> list)
{
for(int i = 0; i < list.Count; i++)
{
list[i] = 23;
}
}
Returns 23, 23, 23,
Java below:
public static void main(String[] args)
{
List<Integer> goods = new ArrayList<Integer>();
goods.add(1); goods.add(2); goods.add(3);
ChangeThings(goods);
for(int item: goods)
{
System.out.println(item);
}
}
private static void ChangeThings(List<Integer> goods)
{
for(int item: goods)
{
item = 23;
}
}
Returns 1, 2, 3.
I don’t understand the discrepancy.
You’re seeing the difference between a
foreachloop and a regularforloop.Your Java code only assigns the local
itemvariable; it doesn’t actually modify the list.If you write
goods.set(i, 23), you will modify the list.