java中的可变和不可变String之间有什么区别 [英] What is difference between mutable and immutable String in java

查看:136
本文介绍了java中的可变和不可变String之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,

可以更改可变字符串,并且
不能更改不可变字符串。

a mutable string can be changed, and an immutable string cannot be changed.

这里我想像这样更改String的值,

Here I want to change the value of String like this,

String str="Good";
str=str+" Morning";

,其他方式是,

StringBuffer str= new StringBuffer("Good");
str.append(" Morning");

在这两种情况下我都试图改变 str的价值。任何人都可以告诉我,这两种情况有什么区别,并给我清楚可变和不可变对象的图片。

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.

推荐答案

案例1:



Case 1:

String str = "Good";
str = str + " Morning";

在上面的代码中你创建了3 String 对象。

In the above code you create 3 String Objects.


  1. 好它进入 String Pool

  2. 早上它也会进入 String Pool

  3. 早安通过连接好创建和早晨。这家伙继续

  1. "Good" it goes into the String Pool.
  2. " Morning" it goes into the String Pool as well.
  3. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.

注意:字符串始终不可变。没有,像可变字符串这样的东西。 str 只是引用,最终指向早安。实际上, 1 对象上工作。你有 3 distinct 字符串对象。

Note: Strings are always immutable. There is no, such thing as a mutable String. str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects.

StringBuffer str = new StringBuffer("Good"); 
str.append(" Morning");

StringBuffer 包含一系列字符。 String 相同。
上面的代码为现有数组添加了字符。实际上, StringBuffer 是可变的,其 String 表示不是。

StringBuffer contains an array of characters. It is not same as a String. The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't.

这篇关于java中的可变和不可变String之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆