一:compareTo 比较数据的大小
compareTo(string)
compareTo(object string)
compareToIgnoreCase(String)
通过使用上面的函数比较两个字符串,并返回一个int类型。若字符串等于参数字符串、则返回0,字符串小于参数字符串、则返回值小于0,字符串大于参数字符串、返回值大于0。
判断字符串大小的依据是根据他们在字典中的顺序决定的。
示例:
/**
* Java字符串比较大小
*/
public class StringA {
public static void main(String[] args){
String str = "String";
String anotherStr = "string";
Object objstr = str;
System.out.println(str.compareTo(anotherStr));
System.out.println(str.compareToIgnoreCase(anotherStr));
System.out.println(str.compareTo(objstr.toString()));
}
}
结果:
-32
0
0
二:使用equals(),“==”方式比较字符串
- 对于基本类型,==比较的是值;
- 对于引用类型,==比较的是两个对象地址值是否相同;
- equals不能用于基本类型的比较;
- 如果没有重写equals,equals默认比较是地址值就相当于==;
- 如果重写了equals方法,equals比较的是字符串的内容是否相同;
示例:
public class StringA {
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println("s1:" + s1);
System.out.println("s2:" + s2);
System.out.println("s3:" + s3);
System.out.println("s4:" + s4);
System.out.println("----------比较内容是否相等---------------");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s3.equals(s4));
System.out.println("----------比较引用地址是否相等---------------");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s3 == s4);
}
}
结果:
s1:hello
s2:hello
s3:hello
s4:hello
----------比较内容是否相等---------------
true
true
true
----------比较引用地址是否相等---------------
true
false
false