简体   繁体   English

字符串不能改变。 但是int,char可以改变

[英]String can't change. But int, char can change

I've read that in Java an object of type String can't change. 我已经读过,在Java中,String类型的对象无法更改。 But int and char variables can. 但int和char变量可以。 Why is it? 为什么? Can you give me an example? 能给我举个例子?

Thank you. 谢谢。 (I am a newer -_- ) (我是新手-_-)

As bzabhi said, strings are immutable in Java. 正如bzabhi所说,字符串在Java中是不可变的。 This means that a string object will never change. 这意味着字符串对象永远不会改变。 This does not mean you can not change string variables, just that you cannot change the underlying memory representation of the string. 这并不意味着您无法更改字符串变量,只是您无法更改字符串的基础内存表示形式。 for an example: 举个例子:

String str = "Hello";
str += " World!";

Following the execution of these lines, str will point to a new string in memory. 在执行这些行之后,str将指向内存中的新字符串。 The original "Hello" string still exists in memory, but most likely it will not be there for long. 原始的“Hello”字符串仍然存在于内存中,但很可能它不会存在很长时间。 Assuming that there are no extenuating circumstances, nothing will be pointing at the original string, so it will be garbage collected. 假设没有任何情有可原的情况,没有任何东西会指向原始字符串,因此它将被垃圾收集。

I guess the best way to put this would be to say that when line 2 of the example executes, a new string in memory is created from the concatenation of the original string and the string being added to it. 我想最好的方法就是说当示例的第2行执行时,内存中的新字符串是从原始字符串的串联和添加到其中的字符串创建的。 The str variable, which is just a reference to a memory location, is then changed to point at the new variable that was just created. 然后将str变量(仅仅是对内存位置的引用)更改为指向刚刚创建的新变量。

I am not particularly knowledgeable on the point, but, as I understand it, this is what happens with all "non-primitive" values. 我并不是特别了解这一点,但是,据我所知,这就是所有“非原始”价值所发生的事情。 Anything that at some point derives from Object follows these rules. 在某些时候从Object派生的任何东西都遵循这些规则。 Primitive values, such as ints, bools, chars, floats and doubles allow the actual value in memory to be changed. 原始值,例如int,bools,chars,float和double,允许更改内存中的实际值。 So, from this: 所以,从这个:

int num = 5;
num += 2;

the actual value in memory changes. 内存中的实际值会发生变化。 Rather than creating a new object and changing the reference, this code sample will simply change the value in memory for the num variable. 此代码示例不是创建新对象并更改引用,而只是更改num变量的内存中的值。

As for why this is true, it is simply a design decision by the makers of Java. 至于为什么这是真的,它只是Java制造商的设计决定。 I'm sure someone will comment on why this was made, but that isn't something I know. 我相信有人会评论为什么会这样做,但这不是我所知道的。

int and char can't change either. int和char也不能改变。 As with strings, you can put a different value into the same variable, but an integer itself doesn't change. 与字符串一样,您可以将不同的值放入同一个变量中,但整数本身不会更改。 3 will always be 3; 3将永远是3; you can't modify it to be 4. 你无法将其修改为4。

String is an immutable type (the value inside of it cannot change). String是一个不可变类型(其中的值不能更改)。 The same is true for all primitive types (boolean, byte, char, short, int, long, float, and double). 所有原始类型(boolean,byte,char,short,int,long,float和double)都是如此。

int    x;
String s;

x = 1;
x = 2;
s = "hello";
s = "world";
x++; // x = x + 1;
x--; // x = x - 1;

As you can see, in no case can you alter the constant value (1, 2, "hello", "world") but you can alter where they are pointing (if you warp your mind a bit and say that an int variable points at a constant int value). 正如你所看到的,在任何情况下你都不能改变常数值(1,2,“你好”,“世界”),但你可以改变他们指向的位置(如果你扭曲了一下你的思绪并说一个int变量点在一个恒定的int值)。

I'm not sure that it is possible to show (by example) that Strings cannot change. 我不确定是否可以(通过示例)显示字符串无法更改。 But you can confirm this by reading the description section of Javadoc for the String class , then reading the methods section and noting that there are no methods that can change a String. 但是您可以通过阅读String类Javadoc的描述部分,然后阅读methods部分并注意到没有可以更改String的方法来确认这一点。

EDIT : There are many reasons why Strings are designed to be immutable in Java. 编辑 :为什么Strings被设计为在Java中不可变的原因有很多。 The most important reason is that immutable Strings are easier to use correctly than mutable ones. 最重要的原因是不可变字符串比可变字符串更容易正确使用。 And if you do need the mutable equivalent of a String for some reason, you can use the StringBuilder (or StringBuffer) class. 如果由于某种原因确实需要可变等效的String,则可以使用StringBuilder(或StringBuffer)类。

It's also worthwhile to note that since strings are immutable, that if they are passed into a method, they can't be modified inside of the method and then have those changes seen outside of the method scope. 值得注意的是,由于字符串是不可变的,如果将它们传递给方法,则不能在方法内修改它们,然后在方法范围之外看到这些更改。

public void changeIt(String s) {
    // I can't do anything to s here that changes the value 
    // original string object passed into this method
} 

public void changeIt(SomeObject o) {
    // if SomeObject is mutable, I can do things to it that will 
    // be visible outside of this method call
} 

这篇小文章可能比我能更好地解释它: http//www.jchq.net/tutorial/09_02Tut.htm

Strings are immutable in java . 字符串在java是不可变的。 Nevertheless, you can still append or prepend values to strings. 不过,您仍然可以为字符串附加或前置值。 By values, I mean primitive data types or other strings. 通过值,我的意思是原始数据类型或其他字符串。

However, a StringBuffer is mutable, ie it can be changed in memory (a new memory block doesn't have to be allocated), which makes it quite efficient. 但是, StringBuffer是可变的,即它可以在内存中更改(不必分配新的内存块),这使得它非常有效。 Also, consider the following example: 另外,请考虑以下示例:

StringBuffer mystringbuffer = new StringBuffer(5000);

for (int i = 0; i<=1000; i++)
{
    mystringbuffer.append ( 'Number ' + i + '\n');
}

System.out.print (mystringbuffer);

Rather than creating one thousand strings, we create a single object ( mystringbuffer ), which can expand in length. 我们不是创建一千个字符串,而是创建一个可以扩展的单个对象( mystringbuffer )。 We can also set a recommended starting size (in this case, 5000 bytes), which means that the buffer doesn't have to be continually requesting memory when a new string is appended to it. 我们还可以设置一个推荐的起始大小(在这种情况下,5000字节),这意味着缓冲区不必在添加新字符串时不断地请求内存。

While a StringBuffer won't improve efficiency in every situation, if your application uses strings that grow in length, it would be efficient. 虽然StringBuffer不会在每种情况下提高效率,但如果您的应用程序使用长度增长的字符串,那么效率会很高。 Code can also be clearer with StringBuffer s, because the append method saves you from having to use long assignment statements. StringBuffer的代码也可以更清晰,因为append方法使您不必使用长赋值语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM