java - 为什么用一些字符串文字与其他最终的字符串变量连接来初始化字符串变量?
问题描述
此代码打印“B”。它不应该什么都不打印吗?我读过连接(+)就像执行一个方法,因此它会产生新的字符串,但这里不是这样。我认为这可能是因为 def 变量是最终的,但是带有 def 变量的复合运算符的工作方式不同......
String abcdef = "abcdef";
final String def = "def";
String a = "abc";
a += def;
String b = "abc" + def;
String c = "abc";
c = c + def;
if(abcdef == a) {
System.out.println("A");
}
if(abcdef == b) {
System.out.println("B");
}
if(abcdef == c) {
System.out.println("C");
}
解决方案
我假设您意识到您应该将 Strings 与equals
and not进行比较==
。但是,请查看字符串的标识 hashCodes。 abcdef
并b
有相同的。这就是为什么它们是相等的使用==
它们从内部缓存中引用相同的对象。
String abcdef = "abcdef";
final String def = "def";
String a = "abc";
a += def;
String b = "abc" + def;
String c = "abc";
c = c + def;
System.out.println("a = " + System.identityHashCode(a)
+ " abcdef = " + System.identityHashCode(abcdef));
System.out.println("b = " + System.identityHashCode(b)
+ " abcdef = " + System.identityHashCode(abcdef));
System.out.println("c = " + System.identityHashCode(c)
+ " abcdef = " + System.identityHashCode(abcdef));
if (abcdef == a) {
System.out.println("A");
}
if (abcdef == b) {
System.out.println("B");
}
if (abcdef == c) {
System.out.println("C");
}
印刷
a = 925858445 abcdef = 798154996
b = 798154996 abcdef = 798154996
c = 681842940 abcdef = 798154996
B
推荐阅读
- android - Google 云存储 - 从 Android 应用下载对象
- elasticsearch - 创建 ElasticSearch 域时出错:ValidationException:身份验证错误
- css - Flex 在较大的断点处包装项目,而在最小处溢出滚动
- flutter - 错误:入口点不包含主函数 Flutter
- mysql - 通过 AWS RDS 在 Kubernetes 上使用 MySQL 的 SonarQube
- python - 使用 jupyter-matplotlib 时删除工具栏和图形标题
- excel - 在 Excel 中使用条件格式仅在满足 2 个条件时才格式化单元格
- tfs - 拉取请求权限
- python - 我如何为我的工作部署这个应用程序:EC2、Elastic Beanstalk,完全是其他东西?
- php - 数据库连接和 SELECT