在 Java 中,所有字符串都是immutable(不能更改)。 当你试图修改一个字符串时,你真正在做的是创建一个新的。
我们可以通过以下方式创建字符串对象
-
使用字符串字面量
String str="java";
-
使用新关键字
String str = new String("java");
-
使用字符数组
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
字符串不变性,简单来说就是不可修改或不可改变
举个例子
我正在将值初始化为字符串文字 s
String s="kumar";
下面我将使用 hashcode() 显示位置地址的十进制表示
System.out.println(s.hashCode());
只打印一个字符串 s 的值
System.out.println("value "+s);
好的,这次我将值“kumar”初始化为 s1
String s1="kumar"; // what you think is this line, takes new location in the memory ???
好的,让我们通过显示我们创建的 s1 对象的哈希码来检查
System.out.println(s1.hashCode());
好的,让我们检查下面的代码
String s2=new String("Kumar");
System.out.println(s2.hashCode()); // why this gives the different address ??
好的,最后检查下面的代码
String s3=new String("KUMAR");
System.out.println(s3.hashCode()); // again different address ???
是的,如果您看到字符串“s”和“s1”具有相同的哈希码,因为“s”和“s1”持有的值与“kumar”相同
让我们考虑一下 String 's2' 和 's3' 这两个 Strings hashcode 在某种意义上看起来是不同的,它们都存储在不同的位置,因为您看到它们的值不同。
因为 s 和 s1 哈希码是相同的,因为它们的值相同并且存储在相同的位置。
示例 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());
}
}
示例 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());
}
}
好,我们来看看mutable和immutable有什么区别。
可变(它会改变)与不可变(它不能改变)
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());
}
}
还有什么问题吗??请写在...