Home > Java > javaTutorial > body text

How to implement deep copy of string in java

王林
Release: 2023-04-27 15:19:14
forward
1661 people have browsed it

How to implement deep copy of a string?

Since strings are immutable, you can directly use the "=" operator to copy one string to another string , and do not affect each other.

public class JavaStringCopy {     public static void main(String args[]) {         String str = "沉默王二";         String strCopy = str;          str = "沉默王三";         System.out.println(strCopy);     } }
Copy after login

The output is as follows:

沉默王二
Copy after login

This example is almost the same as the previous example that proved that strings are immutable, right? This is indeed because strings are immutable, If it is a mutable object, you should pay attention to deep copying. It is best to use the new keyword to return a new object.

public Book getBook() {     Book clone = new Book();     clone.setPrice(this.book.getPrice());     clone.setName(this.book.getName());     return clone; }
Copy after login

The above is the detailed content of How to implement deep copy of string in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!