java 字符串 复制_Java字符串复制

java 字符串 复制

Sometime back I was asked how to copy a String in java. As we know that String is an immutable object, so we can just assign one string to another for copying it. If the original string value will change, it will not change the value of new String because of immutability.

有时,我被问到如何在Java中复制字符串。 我们知道String是一个不可变的对象,因此我们可以将一个字符串分配给另一个字符串以进行复制。 如果原始字符串值将更改,则由于不变性,它将不会更改新String的值。

Java字符串复制 (Java String Copy)

Here is a short java String copy program to show this behavior.

这是一个简短的Java String复制程序,用于显示此行为。

 
 
 
  1. package com.journaldev.string;
  2.  
  3. public class JavaStringCopy {
  4.  
  5. public static void main(String args[]) {
  6. String str = "abc";
  7.  
  8. String strCopy = str;
  9.  
  10. str = "def";
  11. System.out.println(strCopy); // prints "abc"
  12.  
  13. }
  14. }
 

Note that we can perform direct assignment of one variable to another for any immutable object. It’s not limited to just String objects.

请注意,对于任何不可变的对象,我们都可以将一个变量直接分配给另一个变量。 它不仅限于String对象。

However, if you want to copy a mutable object to another variable, you should perform deep copy.

但是,如果要将可变对象复制到另一个变量,则应执行Deep copy 。

Java字符串复制备用方法 (Java String Copy Alternate Methods)

There are few functions too that can be used to copy string. However it’s not practical to use them when you can safely copy string using assignment operator.

也很少有功能可用于复制字符串。 但是,当您可以使用赋值运算符安全地复制字符串时,使用它们并不实际。

  1. Using String.valueOf() method
     
    1. String strCopy = String.valueOf(str);
    2.  
    3. String strCopy1 = String.valueOf(str.toCharArray(), 0, str.length()); //overkill*2
     

     

    使用String.valueOf()方法
  2. Using String.copyValueOf() method, a total overkill but you can do it.
     
    1. String strCopy = String.copyValueOf(str.toCharArray());
    2.  
    3. String strCopy1 = String.copyValueOf(str.toCharArray(), 0, str.length()); //overkill*2
     

     

    使用String.copyValueOf()方法,完全可以解决问题,但是您可以做到。
valueOf and valueOf和 copyValueOf methods are useful. copyValueOf方法很有用。

翻译自: https://www.journaldev.com/20811/java-string-copy

java 字符串 复制

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章