考虑下面的例子。

String str = new String();

str  = "Hello";
System.out.println(str);  //Prints Hello

str = "Help!";
System.out.println(str);  //Prints Help!

在Java中,String对象是不可变的。那么为什么对象str可以被赋值为"Help!"呢?这难道不是与Java中字符串的不变性相矛盾吗?有人能给我解释一下不变性的确切概念吗?

编辑:

好的。我现在明白了,但还有一个问题。下面的代码呢:

String str = "Mississippi"; 
System.out.println(str); // prints Mississippi 

str = str.replace("i", "!"); 
System.out.println(str); // prints M!ss!ss!pp! 

这是否意味着将再次创建两个对象(“Mississippi”和“M!ss!ss!pp!”),并且在replace()方法之后引用str指向不同的对象?


当前回答

str第一次引用的字符串对象没有被改变,你所做的只是让str引用一个新的字符串对象。

其他回答

Use:

String s = new String("New String");
s.concat(" Added String");
System.out.println("String reference -----> "+s); // Output: String reference -----> New String

如果你看到这里我使用concat方法来改变原始字符串,即“新字符串”与字符串“添加的字符串”,但我仍然得到了输出,因此它证明了你不能改变string类对象的引用,但如果你通过StringBuilder类做这件事,它将工作。它列在下面。

StringBuilder sb = new StringBuilder("New String");
sb.append(" Added String");
System.out.println("StringBuilder reference -----> "+sb);// Output: StringBuilder reference -----> New String Added String

Java中的String在Immutable和Final中只是意味着它不能被更改或修改:

案例1:

class TestClass{  
 public static void main(String args[]){  
   String str = "ABC";  
   str.concat("DEF");  
   System.out.println(str);  
 }  
} 

输出:美国广播公司(ABC) 原因:对象引用str没有改变,实际上是一个新对象 在池中创建了“DEF”,它根本没有引用 (也就是失去了)。

案例2:

class TestClass{  
 public static void main(String args[]){  
   String str="ABC";  
   str=str.concat("DEF");  
   System.out.println(str);  
 }  
}  

输出:六边形ABCDEF 原因:在这种情况下,str现在引用一个新对象“ABCDEF” 因此它打印ABCDEF,即前一个str对象“ABC”在池中丢失,没有引用。

字符串是不可变的。这意味着我们只能改变引用。


String a = "a";
System.out.println("String a is referencing to "+a); // Output: a

a.concat("b");
System.out.println("String a is referencing to "+a); // Output: a

a = a.concat("b");
System.out.println("String a has created a new reference and is now referencing to "+a); // Output: ab

不可变性意味着实例化对象的值不能改变,你永远不能把“Hello”变成“Help!”

变量str是一个对象的引用,当你给str赋一个新值时,你没有改变它引用的对象的值,你引用的是一个不同的对象。

Object字符串-方法本身是“不可变的”。 此操作不会产生任何更改:“字母”。替换(“bbb”、“aaa”);“

但是分配数据会导致Strings内容的改变:

    letters = "aaa";
    letters=null;
    System.out.println(letters);
    System.out.println(oB.hashCode());
    System.out.println(letters);
    letters = "bbbaaa";
    System.out.println(oB.hashCode());
    System.out.println(letters);

// string Object的hashcode不变。