zoukankan      html  css  js  c++  java
  • 深度解析java.lang.String类的equal(Object obj)方法 和compareTo(String anatherString)方法

     一.首先先来看下java.lang.String这个类下面的equals方法是如何实现的。

    public boolean equals(Object anObject) {
            if (this == anObject) {  //判断对象的地址是否一致
                return true;  
            }
            if (anObject instanceof String) {  //判断anObject是否是String类型
                String anotherString = (String)anObject;  //类型转化
                int n = value.length;
                if (n == anotherString.value.length) {//判断字符数组的长度是否一致
                    char v1[] = value;
                    char v2[] = anotherString.value;
                    int i = 0;
                    while (n-- != 0) {   //从左到右挨个比较字符是否相等
                        if (v1[i] != v2[i])
                            return false;
                        i++;
                    }
                    return true;
                }
            }
            return false;
        }

    1.对象的地址是一致的返回true

    2.对象地址不一致但是类型一致,字符数组的长度一致且每个字符都相等,则返回true

    3.如果参数不是String类型则返回false

    4.如果参数是String类型但是字符数组的长度不一致则返回false

    5.如果参数是String类型,字符数组的长度一致,但是从左到右如果遇到字符不一致则返回false

    二.java.lang.String这个类下面的compareTo方法是如何实现的。

    public int compareTo(String anotherString) {
            int len1 = value.length;
            int len2 = anotherString.value.length;
            int lim = Math.min(len1, len2);
            char v1[] = value;
            char v2[] = anotherString.value;
    
            int k = 0;
            while (k < lim) {
                char c1 = v1[k];
                char c2 = v2[k];
                if (c1 != c2) {
                    return c1 - c2;
                }
                k++;
            }
            return len1 - len2;
        }

    按字典顺序比较两个字符串,比较是基于字符串中每个字符的unicode值。

    如果字符串对象的字典顺序先于形参字符串,结果是负整数

    如果字符串对象的字典顺序后于形参字符串,结果是正整数

    如果字符串是相等的,结果是0

    当equals(Object)返回true的时候,compareTo 确定返回0

    这是字段顺序的定义:如果两个字符串是不同的,要么是在相同的索引(索引在两个字符串中都是有效的)处有不同的字符,要么他们的长度是不同的,要么长度也不同,相同索引位置的字符也不同,如果他们在一个或者多个索引处有不同的字符,用k表示最小的索引,在位置k拥有较小值(使用<操作符确定)的字符串在字段顺序上先于另一个字符串,在这种情况下,compareTo()返回两个字符串在位置k的两个字符的差值,也就是this.charAt(k)-anotherString.charAt(k)

    如果他们在任何位置都拥有相同的字符,那么那个短的字符串在字典顺序上先于较长的字符串,这这种情况下,compareTo 返回这两个字符串长度的差值,也就是this.length-anotherString.length()

    Specified by:compareTo in interface Comparable<String>

    Parameters:anotherString - the String to be compared.

    Returns:the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

  • 相关阅读:
    jquery冲突细节
    最懂中文的H5前端框架amazeUI
    IT Girl
    json_encode注意
    YII2 Activedataprovider 类分页的使用
    Yii框架,在页面输出执行sql语句,方便调试
    yii2的GridView和ActiveDataProvider具体使用
    文件压缩工具类
    将dubbo中使用的动态代理作为工具类
    spring中使用动态代理(AOP)
  • 原文地址:https://www.cnblogs.com/zhaijing/p/9497748.html
Copyright © 2011-2022 走看看