Java关于Strning的indexOf与contains方法的区别

博客探讨了Java中String类的indexOf和contains方法的效率。大部分测试结果显示indexOf方法通常执行更快。经源码分析,contains方法实际上是调用了indexOf,并进行了一次额外的判断。在Java 8和11的源码中,contains方法的实现略有不同,但核心逻辑不变,都是基于indexOf。因此,选择哪个方法取决于具体应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

偶然看到一些文章有关java中String的indexOf与contains效率的比较,翻了一些大多数测试表示indexOf效率相对contains很快,随即翻看源码的过程发现contains方法其实是直接调用的indexOf方法,所以个人觉得还是看方法的用途,contains也就比indexOf多一层方法栈,附源码:

//jdk8
/**
 * Returns true if and only if this string contains the specified
 * sequence of char values.
 *
 * @param s the sequence to search for
 * @return true if this string contains {@code s}, false otherwise
 * @since 1.5
 */
public boolean contains(CharSequence s) {
    return indexOf(s.toString()) > -1;
}

//jdk11
/**
 * Returns true if and only if this string contains the specified
 * sequence of char values.
 *
 * @param s the sequence to search for
 * @return true if this string contains {@code s}, false otherwise
 * @since 1.5
 */
public boolean contains(CharSequence s) {
    return indexOf(s.toString()) >= 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值