如何让理解字符串常量的不可变

1、字符串常量不可变

字符串是一种不可变对象,指的是它的内容不可改变,但是引用是可以改变的,String类内部实现也是基于char[]来实现的,并且源码中String类是私有的并没有提供方法修改类内部的字符数组

private final char value[];
String str = "hello";
str += "world";
str += "!!!";
//hello word!!!

形如+=这样的操作表面是修改了字符串,其实不是。
注意这里做了两次拼接,会产生两个临时的对象,程序结束后,这些临时对象就会被垃圾回收器回收。
在这里插入图片描述

2、关于==和equals

==:比较引用类型的实际比较的是引用的值
equals:比较引用类型的默认的也是比较地址值但其实String类是重写了equals方法的所以这里其实比较的是内容是否相同

String s1 = "hello";
String s2 = "world";
String s3 = "helloword";
System.out.println(s3 == s1 + s2);//false

字符串如果是变量相加,是先分别给变量开空间,再拼接
字符串如果是常量,是在编译器先确定好,然后再常量池找,如果有就返回,没有就创建

System.out.println(s3.equals((s1 + s2)));//true
System.out.println(s3 == "hello" + "world");//true
System.out.println(s3.equals("hello"+"world"));//true

一定不要忘记了这里"hello"+"world"是个常量(常量相加是先把他加起来看有没有,有就直接拿,没有就创建一个再返回)

发布了52 篇原创文章 · 获赞 6 · 访问量 1442

猜你喜欢

转载自blog.csdn.net/qq_40488936/article/details/104899286