0
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 method of String:

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;
}

Since for "FAN" I have used offset as 1,I thought "AN" of "FAN" will be compared with "AN" and return 0.But it did not since compareTo of String returns return len1 - len2;

My question is,what is the purpose of offset in compareTo method? Always offset is 0.Can you also please give an example by having a different offset for either or both?

user104309
  • 690
  • 9
  • 20
  • 1
    Are you talking about java.lang.String? What is CustomString? Is this your code or someone elses? – aioobe Jan 09 '15 at 13:43
  • Yes.I was talking about java.lang.String.I wanted to debug `compareTo` by changing the offset to something other than 0.So I wrote a own class `CustomString` to simulate `java.lang.String`. – user104309 Jan 09 '15 at 13:49

1 Answers1

3

If this is meant to mimic pre-Java7 java.lang.String, the offset field is used to implement a constant-time substring() operation. See Time complexity of Java's substring()

To relate this to your example, "FAN".substring(1, 3) would set count to 2, not 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"

Thus, one.compareTo(two) would evaluate to 0 (since len1 == len2 == 2).

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012