public class CustomString {
public char value[];
public int offset;
public int count;
public int hash;
}
CustomString one = new CustomString();
char valueOne[] = {'A','N'};
one.count = 2;
one.hash = 0;
one.offset = 0;
one.value = valueOne;
CustomString two = new CustomString();
char valueTwo[] = {'F','A','N'};
two.count = 3;
two.hash = 0;
two.offset =1;
two.value = valueTwo;
compareTo(one,two)
字符串的compareTo方法:
public static int compareTo(CustomString one, CustomString two) {
int len1 = one.count;
int len2 = two.count;
int n = Math.min(len1, len2);
char v1[] = one.value;
char v2[] = two.value;
int i = one.offset;
int j = two.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;
}
由于对于“FAN”我使用偏移量为1,我认为“FAN”的“AN”将与“AN”进行比较并返回0。但从compareTo
开始就没有了。的String
返回return len1 - len2;
我的问题是,offset
的目的是什么?在compareTo
方法?偏移量始终为 0。您能否举个例子,其中一个或两个都具有不同的偏移量?
最佳答案
如果这是为了模仿 Java7 之前的 java.lang.String
,则 offset
字段用于实现恒定时间 substring()
操作。请参阅Time complexity of Java's substring()
为了将此与您的示例联系起来,"FAN".substring(1, 3)
会将 count
设置为 2
,而不是 3
:
CustomString two = new CustomString();
char valueTwo[] = {'F','A','N'};
two.value = valueTwo;
two.offset = 1;
two.count = 2; // <------- the number of characters in the string "AN"
因此,one.compareTo(two)
的计算结果为 0
(因为 len1 == len2 == 2
)。
关于java - Java中compareTo的逻辑(offset的作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27861870/