代码如下:
public static void main(String[] args) {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
A a = dispatcherServlet.new A("bb");
dispatcherServlet.da(a); // 此行执行完毕,a.getA()值是bb
System.out.println(a.getA());
}
private A da(A a) {
a = new A("aaaaa");
return a;
}
class A {
private String a;
public A(String a) {
this.a = a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
疑惑如注释。为何da方法里的new值回到main后会丢失?
经学习得出以下结论:
因此:
希望对其它碰到这种问题的人,不明所以的人有所帮助!!哈哈\(^ ^)/
Although Java does not write pointers in plain text, pointers are still used.
is used in the methoddispatcherServlet.da(a); // Although the object a is written here, the reference
Java is divided into objects, and reference objects (or pointers?) to this object.
Example:
Goods a in the warehouse, and the list of goods a qd_a, the list states which warehouse, which area and location in which goods a is located.
Someone changed the data on qd_a and pointed it to item b, but item a was not affected. What was affected was the list of qd_a.
This is what I understand. I don’t know if the explanation is clear. I hope you can correct me.
Change a here to a member variable
Java does not pass by reference, which means that Java cannot let you replace the reference of the entire parameter. C/C++ has reference passing, but you must add the ampersand in front of the parameter.
Java passes by value, not by reference, but by passing the value of the pointer, so it looks like a reference. . .
Inside
This sentence cannot be reflected outside the function. If the value (address) of a is modified within the function, it is useless, but the content of a can be modified
in daFor example, if there is
Then the value you print outside the function is "aaaaa"
Equivalent to C++ like this
Java only passes by value, not by reference
Correct answer, when passing an object, you must remember that what you pass is not the memory address of the object itself, but the value of the object, and this value is the address referenced by the object
I feel like Java passes parameters on a case-by-case basis,
For container objects such as Map, the reference is passed instead of copying the value
The processing of the map container in the function will change to the original caller. This cannot be called passing by value...
It’s true that simple types are passed by value
Posts in 2009
http://ivan-pig.iteye.com/blog/422891
Can this solve lz’s question?
For non-primitive types, the reference is placed on the stack and the object itself is placed on the heap. The reference on the stack will be copied, but the object will not be copied.
If you want to implement reference transfer in Java, you can use boxing, that is, use an array to access.