Question about adding StringBuffer to a set

Source: Internet
Author: User

/*** I thought there was no problem with the simple code below in a large project, but it took me some time to figure out the BUG, this Code simply adds two strings. Let's take a look at the output content. **/@ Testpublic void test () {StringBuffer sb = new StringBuffer (); list list = new ArrayList (); sb. append ("First row data"); list. add (0, sb); sb. delete (0, sb. length (); sb. append ("second row of Data"); list. add (1, sb); System. out. println (list );}










After running the program, you will find that the output content of the program is: see the end. That is to say, the list set does not store the reference value, but stores the reference, however, in Java APIs, public void add (int index, E element) inserts the specified element into the specified position in this list. Move the current element (if any) at this position to the right and all subsequent elements (add its index to 1 ). According to the output result of the program, we can see that the list set gets the specific value pointed to by reference only when the set is output. ([Second row of data, second row of data])

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.