快速了解String类的四种比较方法

58 阅读2分钟

"=="比较

"=="比较的作用:判断是否引用同一个对象。

注意:对于内置类型,==比较的是变量中的值;对于引用类型==比较的是引用中的地址。

public static void main(String[] args) {
    //:对于内置类型,==比较的是变量中的值
    int a = 10;
    int b = 20;
    int c = 10;

    // 对于基本类型变量,==比较两个变量中存储的值是否相同
    System.out.println(a == b);    // false
    System.out.println(a == c);    // true
    
//对于引用类型==比较的是引用中的地址
    String s1 = new String("hey");
    String s2 = new String("hey");

    //String类型存的是地址,即是都是“hey",地址不一样,所以不相等
    System.out.println(s1 == s2);//false

"equals"比较

"equals"的作用是:判断字符串是否相等

String类重写了父类Object中equals方法,Object中equals默认按照==比较,String重写equals方法后,按照如下规则进行比较:

1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true

2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false

3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false

4. 按照字典序,从前往后逐个字符进行比较

image.png

//1.正常的比较情况
public static void main(String[] args) {
String s1 = new String("hey");
String s2 = new String("hey");


//equals是一种比较字符串比较好的方法,它比较的是每一个字符的值
System.out.println(s1.equals(s2));//true

System.out.println("--------------------------------------");

//2.特殊情况

//该类型属于常量串直接赋值,所以使用==比较地址,不会出错
//Java当中有一块很特殊的内存 存储在堆上
//s3的"hello"存放在了常量池中,且s4同为"hello"就不需要放了,所以s3和s4使用的同一个内存
String s3 = "hello";
String s4 = "hello";
System.out.println(s3 == s4);//true
System.out.println(s3.equals(s4));//true

"compareTo"比较

"compareTo"的作用是:判断字符串的大小并输出两者的具体差值

与equals不同的是,equals返回的是boolean类型,而compareTo返回的是int类型。

public static void main(String[] args) {
    //1.对应字符不一样,就看对应字符的ASCII的大小
    String s1 = new String("hello");
    String s2 = new String("hz");


    //s1和s2比较大小
    //s1 > s2 返回 大于0 的数字
    //s1 < s2 返回 小于0 的数字  否则返回0
    System.out.println(s1.compareTo(s2));//-21


    //2.对应字符一样,就比较对应字符的长度
    String s3 = "hello";
    String s4 = "helloabc";

    System.out.println(s3.compareTo(s4));//-3
}

image.png

"compareToIgnoreCase"比较

"compareToIgnoreCase"的作用是:忽略大小写的情况下,判断字符串的大小并输出两者的具体差值

属于compareTo的变种,当初compareTo理解即可。

public static void main(String[] args) {

        String s1 = new String("hello");
        String s2 = new String("Hello");

        System.out.println(s1.equals(s2));                  //false
        System.out.println(s1.equalsIgnoreCase(s2));        //true

        System.out.println(s1.compareTo(s2));               //32
        System.out.println(s1.compareToIgnoreCase(s2));     //0
}