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:
List.of
, Set.of
, and Map.of
methods.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.