I started to read books related to Java. When we see the access permission control, there is a saying that this means not to easily return a reference to a private object. At the beginning, I didn't agree. Who would do this? Doesn't it mean that the control of the private object is handed over? However, when I thought that Java passed everything by reference, I tried the following:Code:
Import java. util. vector;
ClassTest
{
PrivateVector <string> V;
PublicTest ()
{
V =NewVector <string> ();
V. Add ("MLP");
}
PublicVector <string> getvalue ()
{
ReturnV;
}
PublicObject getvaluecopy ()
{
ReturnV. Clone ();
}
Public VoidPrint ()
{
For(String S: V)
{
System. Out. println (s );
}
}
}
Import java. util. vector;
ClassUseprivate
{
Public Static VoidMain (string [] ARGs)
{
Test T =NewTest ();
Vector <string> value = T. getvalue ();
Value. Add ("LXX");
T. Print ();
}
}
My God, when I used T. Print (), I found that the private object was changed! But what if I really want to return a copy of a private object in this case? At this time, I discovered that the original Java clone () method and C ++
Copy constructor is equally important. If the clone () method is implemented in this class, you only need to return v. Clone.