【源码之路】java中关于equals方法和compareTo方法

来源:互联网 发布:主力资金监控软件 编辑:程序博客网 时间:2024/06/11 08:58

关于equals都会经常用到,但是compareTo可能不会经常使用,这里不对两种方法的功能做过多解释,度娘一下出来一堆,直接上源码

equals源码:

public boolean equals(Object anObject) {if (this == anObject) {//这里提高效率    return true;}if (anObject instanceof String) {//这里提高效率    String anotherString = (String)anObject;    int n = count;    if (n == anotherString.count) {//这里提高效率char v1[] = value;char v2[] = anotherString.value;int i = offset;int j = anotherString.offset;while (n-- != 0) {    if (v1[i++] != v2[j++])//关键这里return false;}return true;    }}return false;    }
compareTo源码:

public int compareTo(String anotherString) {int len1 = count;int len2 = anotherString.count;int n = Math.min(len1, len2);char v1[] = value;char v2[] = anotherString.value;int i = offset;int j = anotherString.offset;if (i == j) {    int k = i;    int lim = n + i;    while (k < lim) {char c1 = v1[k];char c2 = v2[k];if (c1 != c2) {//关键这里    return c1 - c2;}k++;    }} else {    while (n-- != 0) {char c1 = v1[i++];char c2 = v2[j++];if (c1 != c2) {//关键这里    return c1 - c2;}    }}return len1 - len2;    }


在“关键这里”可以看到两个方法都是对ASCII码的比较,只不过返回值不同。

所以在面试的过程中可以说一下字符串比较的原理,再顺便把compareTo说一下

原创粉丝点击