10/11/2023 0 Comments Heap vs stack java![]() Just remember that Java method calls copy references to object, not the objects themselves.īy the way you won't be able to add elements to a set returned by Collections.emptySet(). Or more precisely, you can observe the effects of operations on one reference to an object via operations on other references to the same object. Assuming that the two references point to the same object, your "allocation will be preserved". That is because when you call an instance method using the reference in foo or mySet, that method is executed on the object ( HashSet) that the reference refers to. OK - however - if I were to do add or some other operation within my method call, that allocation would be preserved. ![]() for example as the result of the test method. (You could change your code to pass it back. Your code then replaces the reference in mySet with a reference to a newly created HashSet, but this new reference doesn't get passed back to the caller. When you enter the test method, you have two copies of the reference to the HashSet instance created in the main method one in foo and one in mySet. Since Java uses pass by value, this has no effect on the foo variable in the main method. When you create and assign a new set object to mySet, you are simply setting the local variable / parameter. Java arguments are passed "by value", but in the case of an object or array type, the value you are passing is the object/array reference. It is because of the argument passing semantics of Java. Is it because local variables are allocated on the stack, and so my new is blown away when I exit the method?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |