简体   繁体   中英

How do I pass an object as a parameter to a method without affecting the object?

I have an object - Mat - of class Matrix which has an arrayList of Integers. Now I need to pass Mat to a method called getAdjugateMatrix which will use the values of Mat 's ArrayList and return me another Matrix object, but I don't want adjugateMatrix to change Mat at all. How can I achieve that? Will it work if I set Mat to final, do Matrix temp = mat , and then pass temp to getAdjugateMatrix ? TIA

How do i pass an object as a parametre to a method without affecting the object?

You cannot, by default. When you pass an object as an argument, the receiving method can use that object in any manner as it sees fit.

The Comments outlined the possible solutions:

  • Make a deep copy . Pass a new object with a Xerox copy, a clone, of all the data. Now the receiving method can make all the changes it wants without disturbing the original. See the Question, How do I copy an object? .
  • Redesign the class of your passed object to be immutable . For examples of immutable objects, see the java.time classes, and the new List.of , Set.of , and Map.of methods.
  • Document the argument as being under the “honor system” with the receiving method's programmer promising to not modify the passed argument. Obviously this is unreliable as it depends on programmers' awareness and memory. So I would not recommend this approach.

You can use clone

Example

Student18 s1=new Student18(101,"amit");  
  
Student18 s2=(Student18)s1.clone();  

Inside the method create a clone of Mat,do the change you want althen return clone.If you only set Matrix temp = mat,temp will be a reference for accessing mat so when you change temp attributes'values it will affect mat as well that's why you should clone it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM