package com.company;
public class string1 {
public static void main(String[] args) {
System.out.println("===============string========================");
//string类具体有不可变性,因为String类是由final修饰的,所以是不可变的
String str ="hello";
System.out.println(str.hashCode ());
//可以看到,在没有new新的String时,对原来的字符进行修改,String的hashCode值会改变。
// 程序运行时会额外创建一个对象,保存 "helloworld"。当频繁操作字符串时,就会额外产生很多临时变量。
str=str+"world";//helloworld
System.out.println(str);//hello
System.out.println(str.hashCode ());
System.out.println("===============StringBuilder==================");
// 创建一个StringBuilder对象,用来存储字符串
StringBuilder hobby=new StringBuilder("爱慕课");
System.out.println(hobby);
System.out.println(hobby.hashCode ());
//StringBuild的hashCode值不变。
// 由上我们可以看出,String类具有不可变性,其字符串发生改变后会创建新的位置来存储;而StringBuild和StringBuffer是在原有对象上进行修改,其位置不变.
hobby=hobby.append ("123");
System.out.println(hobby);
System.out.println(hobby.hashCode ());
System.out.println("===============StringBuffer==================");
// StringBuffer ,用来存储字符串
StringBuffer hello=new StringBuffer ("love慕课");
System.out.println(hello);
System.out.println(hello.hashCode ());
//StringBufferStringBuffer 是线程安全的,而 StringBuilder 则没有实现线程安全功能,所以性能略高。因此一般情况下,如果需要创建一个内容可变的字符串对象,应优先考虑使用 StringBuilder 类。
hello=hello.append ("123");
System.out.println(hello);
System.out.println(hello.hashCode ());
}
}
运行结果:
===============string========================
99162322
helloworld
-1524582912
===============StringBuilder==================
爱慕课
460141958
爱慕课123
460141958
===============StringBuffer==================
love慕课
1163157884
love慕课123
1163157884
本文详细解析了Java中String,StringBuilder和StringBuffer的特性与使用场景。通过对比,阐述了String的不可变性及其带来的内存开销,StringBuilder和StringBuffer的可变性及线程安全性差异,为开发者提供了选择合适字符串处理类的指导。
1633

被折叠的 条评论
为什么被折叠?



