How do I transfer references to parameters in Java?

Asked 2 years ago, Updated 2 years ago, 124 views

In C#, we use the keyword ref when we use references Is there something like this in Java?

java c# reference

2022-09-22 22:17

1 Answers

In Java, many people are confused because everything is Call by Value.

Object o = "Hello";
mutate(o)
System.out.println(o);

Private void mutate(Objecto) { o = "Goodbye"; } // The parameter o and the passed o are different objects.

In this way, when you pass on an object, you usually think that you pass on a reference, but in reality, you pass on the value of the object The original o will not change to Goodbye, but Hello will be output. If you want Goodbye to be printed from the code above

AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

You have to explicitly inform us that it is a reference in this way.


2022-09-22 22:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.