We know Java supports only "pass by value" .If I pass a collection for eg., a hash table to a function then the modifications to this collection inside the function should not be updated outside this function.But this is not the case in Java?.How do we conclude this?
Please anyone conclude this discussion with a proof...
Passing an object by value to a method means that the method is given a copy of the reference to the object, but it is still possible to access the object members from within the passed reference copy. In the case of collections, this includes invoking the methods to add and remove objects, and of course to modify the contained objects themselves.
You are confusing what "value" means. If you are dealing with objects, this means that any changes of the value of the reference are not reflected to the outside. A straightforward example that shows this behavior is be something like this:
public void foo() {
String s = "example";
String param = s;
bar(param);
assert s == param : "The value of parameter reference was not modified";
assert param.equals("example");
}
public void bar(String param) {
param = "something different";
}
Passing by value does, however, not mean that you cannot change the internal state of the object. This is perfectly possible and has consequences to the outside:
public void foo() {
List<String> l = Arrays.asList("example");
List<String> param = l;
bar(param);
assert s == param : "The value of parameter reference was not modified";
assert !param.get(0).equals("example") : "bar changed the internal state of the parameter";
assert !l.get(0).equals("example") : "bar changed the internal state of the list that is reference equal to the parameter";
}
public void bar(List<String> param) {
param.set(0, "something different");
}
Of course, such changes of the internal state of an object are reflected up all the way in the caller stack, which might lead to unforeseen side effects. This is the reason why the immutable object pattern was introduced. In the Java standard library, java.lang.Object
and java.lang.String
are examples for classes that implement this pattern. However, Java does not provide a language feature where where you can state that a class implements this pattern, so you must rely on JavaDoc and/or source code of the class to be sure an object is immutable.
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