equals 和 compareTo 在 Java 中的区别是什么?
compareTo() 方法按字典顺序比较两个字符串。比较基于字符串中每个字符的 Unicode 值。此 String 对象表示的字符序列按字典顺序与其参数字符串表示的字符序列进行比较。
- 结果为负整数,如果此 String 对象在字典顺序上位于参数字符串之前。
- 结果为正整数,如果此 String 对象在字典顺序上位于参数字符串之后。
- 结果为零,如果字符串相等,则 compareTo 返回 0 且仅当 equals(Object) 方法返回 true 时才会返回 0。
示例
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "point";
// comparing str1 and str2
int retval = str1.compareTo(str2);
// prints the return value of the comparison
if (retval < 0) {
System.out.println("str1 is greater than str2");
} else if (retval == 0) {
System.out.println("str1 is equal to str2");
} else {
System.out.println("str1 is less than str2");
}
}
}输出
str1 is less than str2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP