偶然看到一些文章有关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;
}