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 foreach loop and a regular for loop.
Your Java code only assigns the local item variable; it doesn't actually modify the list.
If you write goods.set(i, 23), you will modify the list.
The "discrepancy" has nothing to do with passing by value. You are using a different kind of loop in Java, the one where the list is not modified. That's why you see the difference.
If you replace the Java loop with a for (int i = 0 ... ) kind or replace the C# loop with a foreach, there would be no differences between the two programs. In fact, C# program will not compile, because assigning the loop variable is a very common error:
foreach(int item in list)
{
item = 23; // <<=== This will not compile in C#
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With