Home >Java >javaTutorial >How to implement deep copy of string in java

How to implement deep copy of string in java

王林
王林forward
2023-04-27 15:19:141727browse

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);     } }

The output is as follows:

沉默王二

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; }

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete