It turns out Java is so dangerous!

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.