java中可变字符串和不可变字符串有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25138587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is difference between mutable and immutable String in java
提问by Raghu
As per my knowledge,
据我所知,
a mutable string can be changed, and an immutable string cannot be changed.
可变字符串可以更改,而不可变字符串不能更改。
Here I want to change the value of String like this,
这里我想像这样改变String的值,
String str="Good";
str=str+" Morning";
and other way is,
而另一种方式是,
StringBuffer str= new StringBuffer("Good");
str.append(" Morning");
In both the cases I am trying to alter the value of str
. Can anyone tell me, what is difference in both case and give me clear picture of mutable and immutable objects.
在这两种情况下,我都试图改变str
. 谁能告诉我,这两种情况有什么区别,并让我清楚地了解可变和不可变对象。
采纳答案by TheLostMind
Case 1:
情况1:
String str = "Good";
str = str + " Morning";
In the above code you create 3 String
Objects.
在上面的代码中,您创建了 3 个String
对象。
- "Good" it goes into the String Pool.
- " Morning" it goes into the String Poolas well.
- "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.
- “好”它进入字符串池。
- “早上”它也进入字符串池。
- 由“Good”和“Morning”串联而成的“Good Morning”。这家伙在堆上。
Note:Strings are always immutable. There is no, such thing as a mutable String. str
is just a referencewhich eventually points to "Good Morning". You are actually, notworking on 1
object. you have 3
distinct String
Objects.
注意:字符串总是不可变的。不存在可变 String 之类的东西。str
仅仅是一个参考,最终指向“早安”。实际上,您不是在处理1
对象。你有3
不同的String
对象。
Case 2:
案例2:
StringBuffer str = new StringBuffer("Good");
str.append(" Morning");
StringBuffer
contains an array of characters. It is notsame as a String
.
The above code adds characters to the existing array. Effectively, StringBuffer
is mutable, its String
representation isn't.
StringBuffer
包含一个字符数组。这是不一样的String
。上面的代码向现有数组添加字符。实际上,StringBuffer
是可变的,它的String
表示不是。
回答by William F. Jameson
When you say str
, you should be careful what you mean:
当你说 时str
,你应该小心你的意思:
do you mean the variable
str
?or do you mean the objectreferenced by
str
?
你是说变量
str
吗?或者你的意思是引用的对象
str
?
In your StringBuffer
example you are not altering the value of str
, and in your String
example you are not altering the state of the String
object.
在您的StringBuffer
示例中,您没有更改 的值str
,在您的String
示例中,您没有更改String
对象的状态。
The most poignant way to experience the difference would be something like this:
体验差异的最尖锐的方式是这样的:
static void change(String in) {
in = in + " changed";
}
static void change(StringBuffer in) {
in.append(" changed");
}
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("value");
String str = "value";
change(sb);
change(str);
System.out.println("StringBuffer: "+sb);
System.out.println("String: "+str);
}
回答by Balduz
In Java, all strings are immutable. When you are trying to modify a String
, what you are really doing is creating a new one. However, when you use a StringBuilder
, you are actually modifying the contents, instead of creating a new one.
在 Java 中,所有字符串都是不可变的。当您尝试修改一个 时String
,您真正在做的是创建一个新的。但是,当您使用 a 时StringBuilder
,您实际上是在修改内容,而不是创建新内容。
回答by Mena
Java String
s are immutable.
JavaString
是不可变的。
In your first example, you are changing the referenceto the String
, thus assigning it the value of two other Strings
combined: str + " Morning"
.
在你的第一个例子,你改变了参考的String
,从而赋予它的其他两个值Strings
组合:str + " Morning"
。
On the contrary, a StringBuilder
or StringBuffer
can be modified through its methods.
相反, a StringBuilder
orStringBuffer
可以通过其方法进行修改。
回答by Philipp Sander
What is difference between mutable and immutable String in java
java中可变字符串和不可变字符串有什么区别
immutable exist, mutable don't.
不可变存在,可变不存在。
回答by Vinay Shanubhag
I modified the code of william with a output comments for better understandable
我用输出注释修改了威廉的代码,以便更好地理解
static void changeStr(String in) {
in = in+" changed";
System.out.println("fun:"+in); //value changed
}
static void changeStrBuf(StringBuffer in) {
in.append(" changed"); //value changed
}
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("value");
String str = "value";
changeStrBuf(sb);
changeStr(str);
System.out.println("StringBuffer: "+sb); //value changed
System.out.println("String: "+str); // value
}
In above code , look at the value of str in both main() and changeStr() , even though u r changing the value of str in changeStr() it is affecting only to that function but in the main function the value is not changed , but it not in the case of StringBuffer..
在上面的代码中,查看 main() 和 changeStr() 中 str 的值,即使您在 changeStr() 中更改了 str 的值,它也仅影响该函数,但在 main 函数中,该值未更改,但它不是在 StringBuffer 的情况下..
In StringBuffer changed value is affected as a global..
在 StringBuffer 中,更改的值会影响为全局..
hence String is immutable and StringBuffer is mutable...
因此 String 是不可变的,而 StringBuffer 是可变的......
In Simple , whatever u changed to String Object will affecting only to that function By going to String Pool. but not Changed...
在 Simple 中,无论你更改为 String Object 的任何内容,都只会影响到该函数。通过转到 String Pool。但没有改变...
回答by CoderCroc
Stringin Java is immutable. However what does it mean to be mutablein programming context is the first question. Consider following class,
Java 中的字符串是不可变的。然而,在编程上下文中可变是什么意思是第一个问题。考虑下课,
public class Dimension {
private int height;
private int width;
public Dimenstion() {
}
public void setSize(int height, int width) {
this.height = height;
this.width = width;
}
public getHeight() {
return height;
}
public getWidth() {
return width;
}
}
Now after creating the instance of Dimension
we can always update it's attributes. Note that if any of the attribute, in other sense state, can be updated for instance of the class then it is said to be mutable. We can always do following,
现在在创建实例后,Dimension
我们可以随时更新它的属性。请注意,如果任何属性,在其他意义上的状态,可以更新为类的实例,那么它被称为是可变的。我们可以随时关注,
Dimension d = new Dimension();
d.setSize(10, 20);// Dimension changed
d.setSize(10, 200);// Dimension changed
d.setSize(100, 200);// Dimension changed
Let's see in different ways we can create a String in Java.
让我们看看我们可以用不同的方式在 Java 中创建一个字符串。
String str1 = "Hey!";
String str2 = "Hyman";
String str3 = new String("Hey Hyman!");
String str4 = new String(new char[] {'H', 'e', 'y', '!'});
String str5 = str1 + str2;
str1 = "Hi !";
// ...
So,
所以,
str1
andstr2
are String literals which gets created in String constant poolstr3
,str4
andstr5
are String Objects which are placed in Heap memorystr1 = "Hi!";
creates"Hi!"
in String constant pool and it's totally different reference than"Hey!"
whichstr1
referencing earlier.
str1
并且str2
是在字符串常量池中创建的字符串文字str3
,str4
并且str5
是放置在堆内存中的字符串对象str1 = "Hi!";
创建"Hi!"
的字符串常量池和它比完全不同的引用"Hey!"
,其str1
前面引用。
Here we are creating the String literal or String Object. Both are different, I would suggest you to read following post to understand more about it.
在这里,我们正在创建字符串文字或字符串对象。两者都不同,我建议您阅读以下帖子以了解更多信息。
In any String declaration, one thing is common, that it does not modify but it gets created or shifted to other.
在任何 String 声明中,有一件事是常见的,即它不会修改,但会被创建或转移到其他地方。
String str = "Good"; // Create the String literal in String pool
str = str + " Morning"; // Create String with concatenation of str + "Morning"
|_____________________|
|- Step 1 : Concatenate "Good" and " Morning" with StringBuilder
|- Step 2 : assign reference of created "Good Morning" String Object to str
How String became immutable ?
String 是如何变得不可变的?
It's non changing behaviour, means, the value once assigned can not be updated in any other way. String class internally holds data in character array. Moreover, class is created to be immutable. Take a look at this strategy for defining immutable class.
这是不变的行为,意味着一旦分配的值不能以任何其他方式更新。String 类在内部将数据保存在字符数组中。此外,类被创建为不可变的。看看这个定义不可变类的策略。
Shifting the reference does not mean you changed it's value. It would be mutable if you can update the character array which is behind the scene in String class. But in reality that array will be initialized once and throughout the program it remains the same.
改变引用并不意味着你改变了它的值。如果您可以更新 String 类中幕后的字符数组,它将是可变的。但实际上该数组将被初始化一次,并且在整个程序中它保持不变。
Why StringBuffer is mutable ?
为什么 StringBuffer 是可变的?
As you already guessed, StringBuffer class is mutable itself as you can update it's statedirectly. Similar to String it also holds value in character array and you can manipulate that array by different methods i.e.append, delete, insert etc. which directly changes the character value array.
正如您已经猜到的,StringBuffer 类本身是可变的,因为您可以直接更新它的状态。与 String 类似,它也将值保存在字符数组中,您可以通过不同的方法操作该数组,即直接更改字符值数组的追加、删除、插入等。
回答by Amit Upadhyay
A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.
可变变量是其值可以就地更改的变量,而在不可变变量中,值的更改不会就地发生。修改不可变变量将重建相同的变量。
回答by Said BAHAOUARY
Mutable means you will save the same referenceto variable and change its contents but immutable you can not change contents but you will declare new referencecontains the new and the old value of the variable
可变意味着您将保存对变量的相同引用并更改其内容但不可变您不能更改内容但您将声明新引用包含变量的新值和旧值
Ex Immutable-> String
Ex 不可变-> 字符串
String x = "value0ne";// adresse one
x += "valueTwo"; //an other adresse {adresse two}
adresse on the heap memory change.
String x = "value0ne";// adresse one
x += "valueTwo"; //an other adresse {adresse two}
堆内存变化的地址。
Mutable-> StringBuffer - StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("valueOne"); // adresse One
sb.append("valueTwo"); // adresse One
可变-> StringBuffer - StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("valueOne"); // adresse One
sb.append("valueTwo"); // adresse One
sb still in the same adresse i hope this comment helps
某人仍然在同一个地址我希望这个评论有帮助
回答by k_kumar
In Java, all strings are immutable(Can't change). When you are trying to modify a String, what you are really doing is creating a new one.
在 Java 中,所有字符串都是不可变的(不能更改)。当您尝试修改 String 时,您真正在做的是创建一个新的.
Following ways we can create the string object
我们可以通过以下方式创建字符串对象
Using String literal
String str="java";
Using new keyword
String str = new String("java");
Using character array
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray);
使用字符串文字
String str="java";
使用新关键字
String str = new String("java");
使用字符数组
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray);
coming to String immutability, simply means unmodifiable or unchangeable
来到字符串不变性,仅仅意味着不可修改或不可更改
Let's take one example
让我们举一个例子
I'm initializing the value to the String literal s
我正在将值初始化为 String literal s
String s="kumar";
Below I'm going to display the decimal representation of the location address using hashcode()
下面我将使用 hashcode() 显示位置地址的十进制表示
System.out.println(s.hashCode());
Simply printing the value of a String s
简单地打印一个 String 的值
System.out.println("value "+s);
Okay, this time I'm inittializing value "kumar" to s1
好的,这次我将值“kumar”初始化为 s1
String s1="kumar"; // what you think is this line, takes new location in the memory ???
Okay let's check by displaying hashcode of the s1 object which we created
好的,让我们通过显示我们创建的 s1 对象的哈希码来检查
System.out.println(s1.hashCode());
okay, let's check below code
好的,让我们检查下面的代码
String s2=new String("Kumar");
System.out.println(s2.hashCode()); // why this gives the different address ??
Okay, check this below code at last
好的,最后检查下面的代码
String s3=new String("KUMAR");
System.out.println(s3.hashCode()); // again different address ???
YES, if you see Strings 's' and 's1' having the same hashcode because the value hold by 's' & 's1' are same that is 'kumar'
是的,如果您看到字符串 's' 和 's1' 具有相同的哈希码,因为 's' 和 's1' 的值与 'kumar' 相同
Let's consider String 's2' and 's3' these two Strings hashcode appears to be different in the sense, they both stored in a different location because you see their values are different.
让我们考虑一下 String 's2' 和 's3' 这两个 Strings 哈希码在某种意义上似乎不同,它们都存储在不同的位置,因为您看到它们的值不同。
since s and s1 hashcode is same because those values are same and storing in the same location.
因为 s 和 s1 哈希码相同,因为这些值相同并且存储在相同位置。
Example 1: Try below code and analyze line by line
示例 1:尝试下面的代码并逐行分析
public class StringImmutable {
public static void main(String[] args) {
String s="java";
System.out.println(s.hashCode());
String s1="javA";
System.out.println(s1.hashCode());
String s2=new String("Java");
System.out.println(s2.hashCode());
String s3=new String("JAVA");
System.out.println(s3.hashCode());
}
}
Example 2: Try below code and analyze line by line
示例 2:尝试下面的代码并逐行分析
public class StringImmutable {
public static void main(String[] args) {
String s="java";
s.concat(" programming"); // s can not be changed "immutablity"
System.out.println("value of s "+s);
System.out.println(" hashcode of s "+s.hashCode());
String s1="java";
String s2=s.concat(" programming"); // s1 can not be changed "immutablity" rather creates object s2
System.out.println("value of s1 "+s1);
System.out.println(" hashcode of s1 "+s1.hashCode());
System.out.println("value of s2 "+s2);
System.out.println(" hashcode of s2 "+s2.hashCode());
}
}
Okay, Let's look what is the difference between mutable and immutable.
好的,让我们看看可变和不可变之间有什么区别。
mutable(it change) vs. immutable (it can't change)
可变(它改变)与不可变(它不能改变)
public class StringMutableANDimmutable {
public static void main(String[] args) {
// it demonstrates immutable concept
String s="java";
s.concat(" programming"); // s can not be changed (immutablity)
System.out.println("value of s == "+s);
System.out.println(" hashcode of s == "+s.hashCode()+"\n\n");
// it demonstrates mutable concept
StringBuffer s1= new StringBuffer("java");
s1.append(" programming"); // s can be changed (mutablity)
System.out.println("value of s1 == "+s1);
System.out.println(" hashcode of s1 == "+s1.hashCode());
}
}
Any further questions?? please write on...
还有什么问题吗??请写在...