宝玛科技网
您的当前位置:首页java 19:不可变字符串和限定字符串(Immutable String and Interned String)

java 19:不可变字符串和限定字符串(Immutable String and Interned String)

来源:宝玛科技网

1 String 的构造

Astringis a sequence of characters. In many languages, strings are treated as an array of characters, but in Java a string is an object. The Stringclass has 11 constructors and more than
40 methods for manipulating strings. Not only is it very useful in programming, but also it is
a good example for learning classes and objects.

You can create a string object from a string literal or from an array of characters. To create a
string from a string literal, use a syntax like this one:
String newString = newString(stringLiteral);

You can also create a string from an array of characters. For example, the following statements create the string “Good Day”:
char[] charArray = {'G','o','o','d',' ','D','a','y'};
String message = newString(charArray)

一个String就是字符系列,在其他语言中,String是以字符数组形式存在, 但java中存在String类,他有11种不同的构造方式,同时有40多种方法,是java中非常重要的一个类。

我们可以通过 String newString = newString(stringLiteral);方式构造例如 String hello=new String("welcome to java");并且java中提供了简单的记法,它等同于 String hello="welcome to java"; 另外,我们也可以将一个字符数组构造为一个String类。例如

char []  charArray={'g','o','o','d',' ','d','a','y'};

String  goodDay=new String(charArray);

其他的构造方法可以参考API文档。

2 不可变字符串

AStringobject is immutable; its contents cannot be changed.Does the following code
change the contents of the string?
String s = "Java";
s = "HTML";
The answer is no. The first statement creates a Stringobject with the content “Java” and
assigns its reference to s. The second statement creates a new Stringobject with the content “HTML” and assigns its reference to s. The first Stringobject still exists after the
assignment, but it can no longer be accessed, because variable snow points to the new
object

一个String 对象的内容是不可变,当你对String 进行修改, 其实他是创建了新的字符串对象,然后将它的引用赋值给了原来的引用变量,这样原来的对象就再也不能访问了,因为他之前的引用已经弃他而去指向了新的字符串对象。他只能等着JVM的自动回收。

例如 String s="java";

        s="hello"; 

这样之后,执行第二句语句时候,并不是去修改了"java"成了“hello”,而是新创建了一个"hello", 也就是在内存中的另一个位置分配了空间,然后s原本是指向了“java”的内存空间,现在他指向了新欢 "hello",而"java"因为已经没有引用指向他所以访问不到,等着被JVM回收。

3 限定字符串

因为String的不可变性,而他又是如此频繁的出现在我们的程序中,素以JVM通融了一下,相同字符串内容的字符串直接量(字面量 literal)使用同一个实例。这就是叫限定字符串。注意这里说的字面量literal(定义:  a literal is a contant value that appears directly in the program),也就是直接在程序中出现的常量。

Since strings are immutable and are ubiquitous in programming, the JVM uses a unique
instance for string literals with the same character sequence in order to improve efficiency and
save memory. Such an instance is called interned.

例如:

public class ImString
{
	public static void main(String [] args)
	{
		String  s1="welcome to java";
		String s2=new String("welcome to java");
		String s3="welcome to java";
		System.out.println(s1==s2);
		System.out.println(s1==s3);
		System.out.println(s2==s3);
		System.out.println(s1.equals(s2));
		System.out.println(s1.equals(s3));
		System.out.println(s2.equals(s3));
		
	}
}

因篇幅问题不能全部显示,请点此查看更多更全内容