String类中的equals方法总结(转载)

转载:https://blog.csdn.net/qq_25827845/article/details/53868815

1.String源码中equals大致写法:

 1 public boolean equals(Object anObject) {
 2 if (this == anObject) {
 3 return true;
 4 }
 5 if (anObject instanceof String) {
 6 String anotherString = (String) anObject;
 7 int n = value.length;
 8 if (n == anotherString.value.length) {
 9 char v1[] = value;
10 char v2[] = anotherString.value;
11 int i = 0;
12 while (n-- != 0) {
13 if (v1[i] != v2[i])
14 return false;
15 i++;
16 }
17 return true;
18 }
19 }
20 return false;
21 }

2. 模仿String equals源码

package cn.ywq.test;
 
class MyString {
    
    char[] value;
    public MyString(char[] value) {
        this.value=value;  //通过构造方法将字符传入
    }
    
    
    public int equalsString(Object obj) {
        if(this==obj){
            return 0;
        }
        
        //若该对象是MyString类型的
        if(obj instanceof MyString){
            MyString string =(MyString) obj;
            int n=this.value.length;
            if (n>string.value.length) {  //先判断长度的关系
                return 1;
            }else if(n<string.value.length){
                return -1;
            }else{   //若长度相等
                 char v1[] = this.value;
                 char v2[] = string.value;
                    int i = 0;
                    while (n-- != 0) {  //按照数组的每一位进行比较
                        if (v1[i] > v2[i]){
                            return 1;
                        }else if(v1[i] < v2[i]){
                            return -1;
                        }
                                
                        i++;
                    }
                    return 0;  //若while循环正常结束,则说明相等,返回0
 
            }
        }
        return -100;  //若传入的不是MyString类型的对象
        
    }
 
}
package cn.ywq.test;
 
public class Test {
 
    public static void main(String[] args) {
        
        char[] value={'a','b','c','d'};
//        char[] value2={'a','b','c','d','e'};
//        char[] value3={'c','b','c','d'};
        char[] value4={'a','b','c',};
        
        MyString myString = new MyString(value);
        MyString s=new MyString(value4);
        int i = myString.equalsString(s); 
        System.out.println(i);
    }
 
}

 

posted @ 2018-12-05 16:58  sunseeker  阅读(3354)  评论(0编辑  收藏  举报