Reputation: 129
I have created a List and added 2 elements to it. I pass this List to a method and initialized the list to new ArrayList()
.
When the method returns I print the size of list but it still shows 2.
public class ValueChange {
public void fun(List<Integer> l1){
l1=new ArrayList<Integer>();
}
public static void main(String[] args){
List<Integer> l1=new ArrayList<Integer>();
l1.add(5);
l1.add(6);
System.out.println("Before = "+l1.size());
ValueChange vc=new ValueChange();
vc.fun(l1);
System.out.println("After = "+l1.size());
}
}
Upvotes: 2
Views: 422
Reputation: 2764
That won't work because of the scope of the parameter.
You want to clear the list:
public void fun(List<Integer> l1){
l1.clear();
}
As other answers have pointed out. Java's pass-by-value is what's causing your issue here. See THIS PAGE for explanation of this.
Upvotes: 1
Reputation: 30528
Java is pass by value but it passes the value of the reference. This basically means that if you reassign a method parameter it does not get reflected in the original object.
Java makes a copy of the original reference when you pass it to a method so if you assign a new value to that reference you won't see the changes outside.
Both references are pointing to the same objet though.
Upvotes: 1
Reputation: 746
Java uses pass by value of reference. Its like you are passing the reference as value. What you have done in the invoked method is you have changed the value of the formal parameter by assigning a new memory to it, It wont reflect in the actual parameter
Upvotes: 3
Reputation: 2871
The line:
l1=new ArrayList<Integer>();
in your fun
method will not actually change the list outside of this method scope. You can change the values inside them, but not reassign a new list to your arguments.
This actually a frequent error in java. If you want to know how the parameters are passed in a method, please read this post.
Upvotes: 7