栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何比较Java中的字符串?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何比较Java中的字符串?

==
测试引用是否相等(它们是否是同一对象)。

.equals()
测试值是否相等(在逻辑上是否为“相等”)。

Objects.equals()null
在调用之前进行检查,
.equals()
因此您不必(在JDK7起可用,在Guava中也可用)。

因此,如果要测试两个字符串是否具有相同的值,则可能要使用Objects.equals()。

// These two have the same valuenew String("test").equals("test") // --> true // ... but they are not the same objectnew String("test") == "test" // --> false // ... neither are thesenew String("test") == new String("test") // --> false // ... but these are because literals are interned by // the compiler and thus refer to the same object"test" == "test" // --> true // ... string literals are concatenated by the compiler// and the results are interned."test" == "te" + "st" // --> true// ... but you should really just call Objects.equals()Objects.equals("test", new String("test")) // --> trueObjects.equals(null, "test") // --> falseObjects.equals(null, null) // --> true

您几乎总是想使用Objects.equals()。在极少数情况下,您知道要处理实习生字符串,可以使用==。

从JLS 3.10.5起。字符串文字:

而且,字符串文字总是引用class的相同实例String。这是因为使用方法将字符串文字(或更广泛地说,是常量表达式的值的字符串(第15.28节))“插入”以便共享唯一的实例String.intern。

在JLS 3.10.5-1中也可以找到类似的示例。

其他要考虑的方法
忽略大小写的String.equalsIgnoreCase()值相等。

String.contentEquals()比较的内容和String任何内容CharSequence(从Java 1.5开始可用)。使您不必在进行相等比较之前将StringBuffer等转换为String,但是将null检查留给了您。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464114.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号