微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java字符串实习,有什么保证?

该问题归结为以下代码
// setup
String str1 = "some string";
String str2 = new String(str1);
assert str1.equals(str2);
assert str1 != str2;
String str3 = str2.intern();

// question cases
boolean case1 = str1 == "some string";
boolean case2 = str1 == str3;

Java标准是否对case1和case2的值提供任何保证?
当然,链接到Java规范的相关部分将是不错的.

是的,我看了所有的SO类似的问题,发现没有重复,因为我没有找到回答这个问题.不,这不是关于通过用==替换equals来“优化”字符串比较的错误的想法.

解决方法

这是你的JLS报价,Section 3.10.5

Each string literal is a reference (§4.3) to an instance (§4.3.1,
§12.5) of class String (§4.3.3). String objects have a constant value.
String literals-or,more generally,strings that are the values of
constant expressions (§15.28)-are “interned” so as to share unique
instances,using the method String.intern.

Thus,the test program consisting of the compilation unit (§7.3):

package testPackage;
class Test {
        public static void main(String[] args) {
                String hello = "Hello",lo = "lo";
                System.out.print((hello == "Hello") + " ");
                System.out.print((Other.hello == hello) + " ");
                System.out.print((other.Other.hello == hello) + " ");
                System.out.print((hello == ("Hel"+"lo")) + " ");
                System.out.print((hello == ("Hel"+lo)) + " ");
                System.out.println(hello == ("Hel"+lo).intern());
        }
}

class Other { static String hello = "Hello"; }

and the compilation unit:

package other;

public class Other { static String hello = "Hello"; }

produces the output: true true true true false true

This example illustrates six points:

Literal strings within the same class (§8) in the same package (§7)
represent references to the same String object (§4.3.1).

Literal strings within different classes in the same package represent
references to the same String object.

Literal strings within different classes in different packages
likewise represent references to the same String object.

Strings computed by constant expressions (§15.28) are computed at
compile time and then treated as if they were literals.

Strings computed by concatenation at run time are newly created and
therefore distinct. The result of explicitly interning a computed
string is the same string as any pre-existing literal string with the
same contents.

结合JavaDoc实习生,您有足够的信息来推断您的两个案例都将返回真实.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


应用场景 C端用户提交工单、工单创建完成之后、会发布一条工单创建完成的消息事件(异步消息)、MQ消费者收到消息之后、会通知各处理器处理该消息、各处理器处理完后都会发布一条将该工单写入搜索引擎的消息、最终该工单出现在搜索引擎、被工单处理人检索和处理。 事故异常体现 1、异常体现 从工单的流转记录发现、
线程类,设置有一个公共资源 package cn.org.chris.concurrent; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @Descrip
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量
Java 9中JShell中的不同启动脚本是什么?
使用Java的位填充错误检测技术
java中string是什么
如何使用Java中的JSON-lib API将Map转换为JSON对象?