【问题标题】:Logic of compareTo in Java (Role of offset)Java中compareTo的逻辑(offset的作用)
【发布时间】:2015-03-07 20:25:45
【问题描述】:
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)

String的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。但它没有因为 StringcompareTo 返回 @987654325 @

我的问题是,offsetcompareTo 方法中的目的是什么?偏移量始终为 0。您能否举个例子,为其中一个或两个设置不同的偏移量?

【问题讨论】:

  • 你说的是java.lang.String吗?什么是自定义字符串?这是您的代码还是其他人的代码?
  • 是的。我在谈论 java.lang.String。我想通过将偏移量更改为 0 以外的值来调试 compareTo。所以我写了一个自己的类 CustomString 来模拟 @987654330 @.

标签: java string offset compareto


【解决方案1】:

如果这是为了模仿 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)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 2011-03-30
    • 2012-03-01
    • 2013-07-02
    • 2018-01-19
    • 1970-01-01
    相关资源
    最近更新 更多